Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

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

By M.K. Verma · 2 May 2022

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