Home > Software design >  React response get data
React response get data

Time:04-14

I wanted to add the data of a Axios response into my useState Array. The problem is that I don't know how to get the data out of the then() function. Basically what I want to do is save the Axios response so that I can use it in my Array. (I'm trying React for the first time)

for (var i = 1; i <= props.max; i  ) {
    const response = Axios.get("http://localhost:3001/content", {id: 1});
    response.then((res) => {
      console.log(res.data[0].title)
    })
    blogs.push({title: "TITLE HERE", text: "text", author: "author", date: "date"}); //I want to insert the title here
}

I already tried:

const [title, setTitle] = useState();
for (var i = 1; i <= props.max; i  ) {
    const response = Axios.get("http://localhost:3001/content", {id: 1});
    response.then((res) => {
      setTitle(res.data[0].title)
    })
}

Heres the complete function:

import React, { useEffect, useState, express, memo } from "react";
import './network.css';
import Axios from 'axios';

function Content(props) {   
  const [blogs, setBlogs] = useState([]);
  const [title, setTitle] = useState();
  /**const [text, setText] = useState();
  const [author, setAuthor] = useState();
  const [date, setDate] = useState();*/
  

  for (var i = 1; i <= props.max; i  ) {
    const response = Axios.get("http://localhost:3001/content", {id: 1});
    response.then((res) => {
      console.log(res.data[0].title)
    })
    blogs.push({title: "TITLE", text: "text", author: "author", date: "date"}); //I want to insert the title here
  }
  

    return (
      <div>
      {blogs.map((blog) => (
      <div >
      <div >
        <h4>{blog.title}</h4>
        <p>{blog.text}</p>
        <div >
          <img alt="user" id="image"/>
          <div >
            <h5>{blog.author}</h5>
            <small>{blog.date}</small>
          </div>
        </div>       
      </div>
  </div>
  ))} 
  </div>
  ); 
  
}

export default Content;

CodePudding user response:

Please add your fetch logic on useEffect hook. Otherwise, fetch logic will be executed in every re-render.

Your app may get frozen.

And you should not change state variable blogs by blogs.push....

use setBlogs function.

And please use className instead of class in DOM.

I see many problems in the code and strongly to read react help before writing any code.

Anyway updated code is here.


function Content(props) {
  const [blogs, setBlogs] = useState([]);
  const [title, setTitle] = useState();
  /**const [text, setText] = useState();
   const [author, setAuthor] = useState();
   const [date, setDate] = useState();*/


  useEffect(() => {
    for (var i = 1; i <= props.max; i  ) {
      const response = Axios.get("http://localhost:3001/content", {id: 1});
      response.then((res) => {
        setBlogs(res.data);
      })
    }
  }, []);




  return (
    <div>
      {blogs.map((blog, key) => (
        <div className="card" index={key}>
          <div className="card-body">
            <h4>{blog.title}</h4>
            <p>{blog.text}</p>
            <div className="user">
              <img alt="user" id="image"/>
              <div className="user-info">
                <h5>{blog.author}</h5>
                <small>{blog.date}</small>
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );

}

export default Content;

CodePudding user response:

You should useEffect hook for fetching data and .then should set it to the state. UseEffect will fetch data when the component is rendered, and store it in the state. Then you can display it in jsx. I recommend reading this article (which shows how to do it with Axios). https://www.freecodecamp.org/news/how-to-use-axios-with-react/

CodePudding user response:

Since Axios is a promise-based HTTP client library you will have to deal with the data only after the response is resolved. This means you have two options . 1) use setBlog inside then function completely (which is mentioned by other answers already) 2) Use async-await syntax(which is just syntactic sugar to the Promise.then() and Promise.catch())

Another thing you need to keep in mind is to try and treat your react state arrays as immutable. So you need to use the spread operator instead of the traditional push method because the push method directly mutates your state array and can lead to some dangerous and error-prone code. It is recommended that you make you react 'state' changes in the useEffect hook or inside a function in the functional component. triggering state changes in the manner you have done can lead to infinite rendering and cause a Runtime Error.

When creating a list in the UI from an array with JSX, you should add a key prop to each child and to any of its’ children. (the key is recommended 'NOT 'to be the index of the array) Below is the code sample to set your array into the state

   useEffect(()=>{
    (async()=>{
      for(let i=0;i<=props.max;i  ){
        let response = await Axios.get("http://localhost:3001/content",{id:1});
        setBlogs((blog)=>[...blog,response.data]);
    }
      
    })();
    });
  • Related