Axios not showing informations on react page

Viewed 46

I would like to use axios to fetch the values from API in react.js, and set it as a form, but it doesn't display any fetched data at all.

export default function Review() {

  const [fetchedData, setFetchedData] = useState([]);
  const [fetchedlanguage, setlanguage] = useState([]);


     useEffect(() => {
       const getStudent = async () => {
         const stu = await axios.get('http://localhost:8000/students/');
         setFetchedData(stu.data.students[0]);
         setlanguage(stu.data.students[0].languages)
       };
       getStudent()
     },[]);

     console.log("student: ", fetchedData);

    const [formdata, setformdata] = useState({
        availability: 6,
        preference:'201, 301',
        experience:'201',
        language:fetchedlanguage[0],
        background:fetchedData.background,
    });

Even though the console.log shows the data correctly, when I set the form here, how come there is no updates on data?

1 Answers

Control it all in one place. You will want to spread the original values over the setformdata because it's immutable. I'm not sure what all the API returns so continue to override each formdata property that you get back from the API.

export default function Review() {
    const [formdata, setformdata] = useState({
        availability: 6,
        preference:'201, 301',
        experience:'201',
        language: 'english',
        background: 'initial-background',
    });

    useEffect(() => {
        const getStudent = async () => {
            const stu = await axios.get('http://localhost:8000/students/');
            const student = stu.data.students.length > 0 ? stu.data.students[0] : {};
            setFormData({
                ...formdata,
                langauge: student.languages,
                // TODO: continue to override the formData from student returned from API
            });
        };
        getStudent()
    }, []);

    // TODO: use formdata to feed into form
    return null;
}
Related