Problem with fetching data in React, Assignment to constant variable

Viewed 52

I just started to learn React and was trying to fetch some random data. i created a useState and have two values : const [name, setName] = useState([]); when i try to do name : response.json(); I get an error that assignment to a constant variable, I'm following a tutorial which is doing the same. surprisingly when I create a constant variable with a different name, it works. I only can't assign the name = await response.json(); Thank you

import React, { useEffect, useState } from "react";
import { ReactDOM } from "react";

const FetchData = () =>{

    const [name, setName] = useState([]);

    const fetchNames = async () =>{

        const url = `https://randomuser.me/api`;

        try {
            
            const response = await fetch(url);
            name = await response.json();
            console.log(name);
           setName(name);
        
        } catch (error) {
            
            console.log(error);
        }
    }

    useEffect(()=>{

        fetchNames();
    },[])

    return(

        <div>

        </div>
    );
}

export default FetchData;
2 Answers

there are 2 things that might help with this confusion

  1. any variable created using const will forever hold the value it had when it was declared, so for eg if we have const x = "", we later can't do something like x = "something else"

  2. in the snippet you shared name is a "state variable". state variables should NEVER be updated directly, state updates must happen through setState function only(i.e. setName in this case)

    this is the part in official docs that talks about it https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly , https://reactjs.org/docs/hooks-state.html#updating-state

Check my example, as I understand you want to use name inside the try as variable not from state so you should add const. I also mapped the response in your render which you can see the results. Here also codesandbox example https://codesandbox.io/embed/friendly-ishizaka-57i66u?fontsize=14&hidenavigation=1&theme=dark

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [name, setName] = useState([]);

  const fetchNames = async () => {
    const url = `https://randomuser.me/api`;

    try {
      const response = await fetch(url);
      constname = await response.json();
      console.log(name);
      setName(name?.results);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchNames();
  }, []);

  return (
    <div>
      {name.map((el) => (
        <>
          <p>{el.email}</p>
          <p>{el.phone}</p>
        </>
      ))}
    </div>
  );
}
Related