Skip to content
Advertisement

won’t let me access json object, what im missing?

So I’m trying to access an array inside an object:

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      isLoading: true
    }
  };

  componentDidMount() {
    fetch(`https://m0n5ter-crawler.herokuapp.com/api/articles/`, {
        method: "GET",
      })
      .then(res => res.json(res))
      .then(res => {
        this.setState({
          data: res._embedded.articles, //this is where im entering the array of objects
          isLoading: false
        })
      })
      .catch((err => {
        console.error(err);
      }));
  }

  render() {
    const {
      isLoading,
      data
    } = (this.state);
    console.log(data);
  }
}

this is what i get in the console log:

(1000) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
0: {groups: Array(1), date: "2015-12-03", url: "https://www.scmagazine.com", title: "", _links: {…}}
1: {groups: Array(1), date: "2018-10-19", url: "https://www.scmagazine.com/", title: "", _links: {…}}
2: {groups: Array(1), date: "2018-06-26", url: "https://www.scmagazine.com", title: ""
[100 … 199]
[200 … 299]
[300 … 399]
[400 … 499]
[500 … 599]
[600 … 699]
[700 … 799]
[800 … 899]
[900 … 999]
length: 1000
__proto__: Array(0)

map isn’t a function, and forEach is undefined, I was trying to do key value on it but the value returned me [object object] or undefined.

What am I missing?

Advertisement

Answer

You initiate data as an object {} and the first render takes data from the initial state.

this.state = {
  data: {},
  isLoading: true
}

Change it to Array

this.state = {
  data: [],
  isLoading: true
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement