Home > database >  How to populate my const before the page renders?
How to populate my const before the page renders?

Time:11-28

I'm pretty new to ReactJS dev and today i'm trying to get some data from an API using Axios. My issue is :

  • I'm trying to de map function on resultData to get what i want inside, but an error is proped and it's showing : resultData.map is not a function
  • If i comment this part of the code and just render the page first, then uncomment, it works and data are shown.

I'm assuming that data is not loaded before the rendering process is over so that's why i get this. But how to make it load before ?

Here my code snippets :

import React, { useState, useEffect } from "react";
import "./App.css";
import axios from "axios";

const Url = "someAPi";

function App() {
  const [baseData, setBaseData] = useState({});
  const [resultData, setResultData] = useState({});

  useEffect(() => {
    getBaseDataWithAxios();
  }, []);

  const getBaseDataWithAxios = async () => {
    const response = await axios.get(Url);
    setBaseData(response.data);
  };

  useEffect(() => {
    getResultDataWithAxios();
  }, []);

  const getResultDataWithAxios = async () => {
    const response = await axios.get(Url);
    setResultData(response.data.result);

  };

  const listItems =  
    resultData.map((d) => <li key={d.value}>{d.value}</li>);

  return (
    <div className="App">
      <header className="App-header">
        <h2>generated fees</h2>
      </header>
      <div className="info-container">
        <h5 className="info-item">{baseData.status}</h5>
        <h5 className="info-item">{baseData.message}</h5>
          <h5 className="info-item">{listItems[1]}</h5>        
      </div>
    </div>
  );
}

export default App; 

The error is thrown on this :

  const listItems =  
    resultData.map((d) => <li key={d.value}>{d.value}</li>);

I know my data can be read since if i comment the listItems and the displaying part in the return, render the page, uncomment everything, it displays the data properly.

Can someone explain to me how to populate data first ? During my research i've seen that this can happen by using Axios.

Thanks a lot !

CodePudding user response:

The useEffect hook always runs after your component function returns in the render cycle.

Try an empty array for your initial value of resultData instead of an empty object:

const [resultData, setResultData] = useState([]);

There is no map built-in method on non-array objects, so during the first execution, you receive that error.

  • Related