0

I want to know why it returns a log <empty string> when I already assigned a value using setState. Does the setState not working? Please help me to fix it.

Here is my code:

const App = (params) => {
    const [data, setData] = useState('');

    const getDatas = async (params) => {
        const { data } = await http().get('todo');
        
        setData('new data');
    }
    
    useEffect(() => {
        getDatas();
        console.log(data);
    }, []);

    return (
        <div className="border">Display text</div>
    );
}
schutte
  • 1,949
  • 7
  • 25
  • 45
  • 1
    Also related (besides the duplicate link): https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately – Henry Woody Nov 09 '20 at 06:50
  • Well, underlying issue is same as the duplicate, but you complicate with `getDatas` being an async function, so `data` is still the current state when logged. The http GET will resolve during *some* future render cycle. – Drew Reese Nov 09 '20 at 06:50

0 Answers0