1

I'm trying to fetch data from a server using the fetch api and displaying this data in an unordered list using uuidv4 as the key, im trying to do this using react's useEffect hook, however, it fetches the data but then it says all my keys are the same, i think useEffect is the cause and i tried adding as the second argument an empty array to prevent the rerendering but then its saying im missing a dependency and when i put the dependency in it rerenders and the uuid's are the same again. i'm not sure what to do im relatively new to hooks.

    import React, { useState, useEffect } from "react";
    import "./App.css";
    const uuidv4 = require("uuid/v4");

    function App() {
      const [country, setCountry] = useState({
        country: []
      });

      useEffect(() => {
        console.log("fetching data");
        fetch("http://localhost:5000/country")
          .then(res => res.json())
          .then(data => setCountry({...country, country: data }));
      }, []);

      return (
        <>
          <ul>
            {country.country.map(item => {
              return <li key={uuidv4}>{item.name}</li>;
            })}
          </ul>
        </>
      );
    }

    export default App;
3
  • 1
    Why are you setting your states to an object? Try setting it to an empty array: const [country, setCountry] = useState({[]}); Commented Aug 6, 2019 at 18:51
  • Isn't uuidv4 a function? Commented Aug 6, 2019 at 18:52
  • yes, i forgot the () Commented Aug 6, 2019 at 18:56

2 Answers 2

1

I think you have to call it to generate the uuid:

 return <li key={uuidv4()}>{item.name}</li>;
Sign up to request clarification or add additional context in comments.

5 Comments

Probably better to map in property of array to prevent different values every render
Im getting this now. Line 12: Assignments to the 'country' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect react-hooks/exhaustive-deps
' Assignments to the 'country' variable from inside React Hook useEffect will be lost after each render.' - no they won't, not if they're assigned via your useState hook
thats the warning in the console
that warning is because you have too many uses of country - your main stateObject and the inner array shouldn't have the same variable names
0

Best way to assign or set the keys when you map over a list is to use index, which you can get from map

return (
        <>
          <ul>
            {country.country.map((item, index) => {
              return <li key={index}>{item.name}</li>;
            })}
          </ul>
        </>
      );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.