Home > database >  React forloop in return after fetch request
React forloop in return after fetch request

Time:08-11

I'm very new to react. I have made a successful get request with axios and now I want to loop through the res.data and display it.

My request looks as followed:


  const [post, setPost] = React.useState(null)

  React.useEffect(() => {
    axios({
      method: 'get',
      url: 'http://localhost:8080/api/tests',
      headers: headers
    }).then((res) => {
      setPost(res.data);
      console.log(res.data)
    })
      .catch((err) => { console.log(err) })
  }, []);

Now inside my return I want to loop through every Object in the res.data array and display the name. I tried by adding a javascript forloop with curly brackets but it didn't worked.


    for (var i = 0; i < post.length; i  ) {
      <p>{i.name}</<p>
    }


Can someone help me how to get every object and render it in the return function?

CodePudding user response:

You need to return something from your loop so you should use map() check the following link https://reactjs.org/docs/lists-and-keys.html. So your code should be something like the following:

Say you have the following component:

const Component = () => {
  // Initialize the data with the datatype in this case it would be an empty array
  // otherwise you will have to check if the array exists before looping
  const [post, setPost] = React.useState([])

  React.useEffect(() => {
    axios({
      method: 'get',
      url: 'http://localhost:8080/api/tests',
      headers: headers
    }).then((res) => {
      setPost(res.data);
      console.log(res.data)
    })
      .catch((err) => { console.log(err) })
  }, []);
    
  return (
    <div className="App">
      {post.map(i => <p>{i.name}</p>)}
    </div>
  );
}

Now you should add a unique key to each of the items returned in a list. Not sure what your data looks like so if there is a unique identifier in each of them you should add this as the key to the item that is returned. So something like {post.map(i => <p key={i.name}>{i.name}</p>)}. But if the name value will have duplicates you would want to use a different unique identifier.

CodePudding user response:

You want to use the .map() method. This allows you to create an array of jsx elements and then return that array in the component.

const Component = () => {
      // Initialize the data with the datatype in this case it would be an empty array
      // otherwise you will have to check if the array exists before looping
      const [post, setPost] = React.useState([])
    
      React.useEffect(() => {
        axios({
          method: 'get',
          url: 'http://localhost:8080/api/tests',
          headers: headers
        }).then((res) => {
          setPost(res.data);
          console.log(res.data)
        })
          .catch((err) => { console.log(err) })
      }, []);
      
      const names = post.map(({name}, index) => <p key={index}>{name}</p>
      // It's important when using .map to create jsx elements from an array,
      // that you include a key prop that is unique. The index of each element 
      // works great in most cases
      return (
        <div className="App">
          // React knows to spread out an array of JSX elements.
          {names}
        </div>
      );
    }
  • Related