Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How manage data when its already fetched by Axios

I am using a database with MySQL and getting it using Axios and a useEffect. Then I pass my database data to a component using a prop. Like this:


const Component = () => {
 //DB
  const urlProxy = "/api/cities";

  //Hooks
  const [data, setData] = useState([]);

  //DB Fetch
  const fetchData = async () => {
    await axios
      .get(urlProxy)
      .then((res) => {
        setData(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() => {
    return () => {
      fetchData();
    };
  }, []);


return (
    <>
      <h1>Cities</h1>
      <Cities api={data} />
    </>
  );
};

Inside of Cities Component I want to make an algorithm to manipulate that data, but I get one empty array (from const [data, setData] = useState([]). After a moment I get the fetched data from database.

const Cities = (api) => {

console.log(data) // First Print: [{api:Array(0)}] then [{api:Array(2)}]

return(
<>
  ...
</>
)

}

So if it prints at first an empty array I would get an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was thinking of using a useTimeout() but i don’t know if there is a better solution, in order to use data after it’s fetched.

>Solution :

All you would need to do is manipluate the data before you set it into your state

and the best way to wait until that is done is to have a loading state that waits for your data to be pulled and then have your useEffect manipulate it.

Something like this should work for you

const urlProxy = "/api/cities";
const Component = () => {
  const [data, setData] = useState();
  const [loading, setLoading] = useState(true);

  //DB Fetch
  const fetchData = async () => {
    await axios
      .get(urlProxy)
      .then((res) => {
        // Manipulate your data here before you set it into state
        const manipluatedData = manipulateData(res.data)
        setData(manipluatedData);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => 
        setLoading(false);
      })
  };

  useEffect(() => {
    return () => {
      fetchData();
    };
  }, []);

if(loading){
   return 'loading....'
}

return (
    <>
      <h1>Cities</h1>
      <Cities api={data} />
    </>
  );
};

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading