Home > Mobile >  Reactjs UseState & UseEffect Messing
Reactjs UseState & UseEffect Messing

Time:10-21

Below is a code i am using to set state for some data:

  const [loader, setLoader] = useState(true);

const [trendData, setTrend] = useState([]);

const [thisMonthData, setThisMonth] = useState([]);

useEffect(() => {
    graphData();
}, [loader]);

async function graphData() {

   
    await getRequest(process.env.REACT_APP_apiUrl   ':0000/abc/xyz').then( (response) => {

        let series = [];
        let months;


        for (let index = 0; index < response.length; index  ) {

             months = response[index]['Month'].split(',');

            series.push(response[index]['Useres'].split(',')); 


        } 

        setTrendMonth(series);
        setThisMonthData(series);
        console.log(thisMonthData);
        
        setLoader(false);
    });

}

And now i am attaching a response getting in console.log(thisMonthData); this. I have tried everything, including thisMonthData in useEffect and other state keys. But everytime data is going blank or missing values.

Whats wrong here.

enter image description here

enter image description here

CodePudding user response:

You are mixing await and then, also try to log thisMonthData when they are changed with a useEffect:

useEffect(() => {
  graphData();
}, [loader]);

useEffect(() => {
  console.log(thisMonthData);
}, [thisMonthData]);

async function graphData() {
  try {
    const response = await getRequest(
      process.env.REACT_APP_apiUrl   ':0000/abc/xyz'
    );
    let series = [];
    let months;

    for (let index = 0; index < response.length; index  ) {
      months = response[index]['Month'].split(',');
      series.push(response[index]['Useres'].split(','));
    }

    setTrendMonth(series);
    setThisMonthData(series);

    setLoader(false);
  } catch (err) {
    console.log(err);
  }
}

CodePudding user response:

Hi Sandeep Singh,

Does the function getRequest() use axios or already does the .json() in some step? Like in the ex:

fetch(myRequest)
  .then((response) => response.json())
  .then((data) => {/***/}
  • Related