skip to Main Content

Learning react so please bear with…

Below code works for me and allows me to set the valueOne as OneOneOne

import etc...

function LoadPage()
{
const [valueOne, setvalueOne] = useState(GetValueOne)  

function GetValueOne()
{
   return 'OneOneOne';
}
}

The issue I am having is I need to make a call to the server to return the actual value of valueOne on page load… So I have changed to the following:

async function GetValueOne()
{
  let oneResult;

  await axios.get(`${getBaseUrl()}/One/GetValueOfOne`)
  .then(res => {
    oneResult= res.data;
  });

 return oneResult;
}

This is now not working as I have changed the function to async to wait for the axios.get request…Can I update the useState to match this?

If not is there another way to do this please?

2

Answers


  1. You should use useEffect in this case.

    You can initialize the state with some dummy value inside useState and add a an effect to update the state value

    function LoadPage() {
      
      const [valueOne, setValueOne] = useState({})  
      
      useEffect(() => {
      
        async function getValueOne() {
          const oneResult = await axios.get(`${getBaseUrl()}/One/GetValueOfOne`)
          setValueOne(oneResult.data)
        }
        getValueOne()
        
      }, [])
      
    }

    Alternatively, if your project is getting bigger

    1. You can take a look at some data fetching/management libraries like Tanstack Query, SWR etc..
    2. You can also take a look at global state solutions like Redux coupled with middlewares like Thunk / Saga for data fetching
    Login or Signup to reply.
  2. You can achieve this using UseEffect hook in ReactJS. You can initialize the state with null value and then update it once the component mounts for the first time.

    Sample code:

     const [valueOne, setValueOne] = useState(null);
      
        useEffect(() => {
        async function fetchData() {
          try {
            const response = await axios.get(`${getBaseUrl()}/One/GetValueOfOne`);
            setValueOne(response.data);
          } catch (error) {
            console.error('Error fetching valueOne:', error);
          }
        }
    
        fetchData();
      }, []); 
    

    On above useEffect, I have added empty square bracket which means useEffect only run once when component mounts.

    Here, is full code implementation:

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    function LoadPage() {
      const [valueOne, setValueOne] = useState(null);
    
      useEffect(() => {
        async function fetchData() {
          try {
            const response = await axios.get(`${getBaseUrl()}/One/GetValueOfOne`);
            setValueOne(response.data);
          } catch (error) {
            console.error('Error fetching valueOne:', error);
          }
        }
    
        fetchData();
      }, []); // Empty dependency array to only run once on mount
    
      return (
        <div>
          <h1>Value of valueOne: {valueOne}</h1>
        </div>
      );
    }
    
    export default LoadPage;
    

    Let me know, If you have any questions.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search