alexa
Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

Why useState is not accepting input received from the GET request in react.js ?

Why useState is not accepting input received from the GET request in react.js ?

Try make your code like this

 import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {
    const [categoryDetail, setCategoryDetail] = useState({});
    const [name, setName] = useState('');
    // const [place, setPlace] = useState('');
    // const [animal, setAnimal] = useState('');
    // const [thing, setThing] = useState('');

    useEffect(() => {
        const fetchCategories = async () => {
            await axios
                .get('https://mocki.io/v1/5a61740b-d272-4943-abe3-908628510020')
                .then((response) => {
                    setCategoryDetail(response.data.categories[0]);
                    setName(response.data.categories[0].categoryName);
                });
        };
        fetchCategories();
    }, []);

    // https://mocki.io/v1/5a61740b-d272-4943-abe3-908628510020
    return (
        <>
            <p>{name}</p>
            <p>{JSON.stringify(categoryDetail)}</p>
        </>
    );
};

export default App; 

And as you see , I am doing call to setName after fetchCategories() inside of async/await call , put other state setters there


98 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online