alar
alar

Reputation: 207

React Cannot read property 'map'

I'm using react hooks and I want to display each count that comes from API. But I'm getting error Cannot read property 'map'

API return json data like:

model: {
  item 1: {
    count: 200
  }
  item2: {
    count: 300
  }
  item 3: {
    count: 400
  }
}

and useEffect looks like:

const [results, setResults] = useStates();

 useEffects(() => {
fetch('api)
.then(results =>{
    return results.json();
}).then(data => {
    let test = data.results.map((item) => {
        return(
            <div>{test.count}</div>
        );
    });
    setResults(test);
});
});

Upvotes: 0

Views: 89

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53964

You can use Object.values() and Array.map() like so:

const data = {
  model: {
    item1: {
      count: 200
    },
    item2: {
      count: 300
    },
    item3: {
      count: 400
    }
  }
};

console.log(Object.values(data.model).map(({
  count
}) => count));

Note that you want to fetch data only on mount useEffect(fn,[]), and also it is not recommended to save the component itself as the state, render it depending on the data:

const App = () => {
  const [results, setResults] = useStates([]);
  useEffect(() => {
    fetch('api')
      .then(results => {
        return results.json();
      })
      .then(data => {
        setResults(Object.values(data.model).map(({ count }) => count));
      });
  }, []);

  return results.map((count,key)=> <div key={key}>{count}</div>);
};

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167220

The .map() is a function present only in arrays and not objects. So for your case, what you can do is, loop through the keys and iterate the object.

useEffect(() => {
  fetch("api")
    .then(results => {
      return results.json();
    })
    .then(data => {
      let test = Object.keys(data.results).map((item, key) => {
        return <div key={key}>{data.results[item].count}</div>;
      });
      setResults(test);
    });
});

And one more thing is, it's useEffect and useState(), you have left a ', there's no test variable. Don't forget to give a key when mapping. I have corrected all the mistakes in your code above.

Upvotes: 4

Related Questions