ImpostorIsAsking
ImpostorIsAsking

Reputation: 73

React iterate json api to setState variable

I have this useState:

const [records, setRecords] = useState([
    { title: "", date: ''}
    ]);

in this useState I'm try to iterate my api record:

useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/events')
      .then((response) => response.json())
      .then((data) => {
        data.map((item) => (
          setRecords({title: item.name, date: item.starts_at })
        ))

      })
  }, console.log(records))

im trying to put my API records to my setRecords and end up to infinite loop.

im newbie in React

Upvotes: 0

Views: 52

Answers (1)

GalAbra
GalAbra

Reputation: 5148

You mixed the scopes. setRecords should be called only once, with the entire new records array:

useEffect(() => {
  fetch('https://jsonplaceholder.typicode.com/events')
    .then((response) => response.json())
    .then((data) => {
      const newData = data.map((item) => (
        { title: item.name, date: item.starts_at }
      ));
      setRecords(newData);
    })
}, []) // This is the dependency array. Not sure why there was a console.log there

Upvotes: 1

Related Questions