0

Why can't I get it as an object (abonnes) from result Getelementbyid? I get the element on JSON.

function Abonnes() {
  const [abonnes, setAbonnes] = useState();

  const getOneAbonnes = (id) => {
    Axios.get(`http://localhost:4000/api/getonea/${id}`).then((response) => {
      setAbonnes(response.data);
      console.log(abonnes); // undefined
    });
  };
}
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
  • React state setter functions are asynchronous. Hence, you won't see its updated value right after setting it. To see the changed value in console log, try this code - `useEffect(() => { console.log(stateValue) }, [stateValue])`. Or, better, you can visualize it using [React Dev Tool](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/). – Ajeet Shah Apr 13 '21 at 14:45
  • Also, see [this](https://github.com/facebook/react/issues/11527#issuecomment-360199710), [this](https://reactjs.org/docs/react-component.html#setstate), [this](https://stackoverflow.com/q/41446560/2873538), [this](https://stackoverflow.com/q/54069253/2873538), [this](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous). – Ajeet Shah Apr 13 '21 at 14:45
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Ajeet Shah Apr 13 '21 at 14:46

2 Answers2

0

because that's how your api is set it returns a JSON file , you can just parse it and you"re ready to go

Axios.get(`http://localhost:4000/api/getonea/${id}`).then((response)=>{
        
        setAbonnes(JSON.parse(response.data));                          
        console.log(abonnes); // this won't log the value you just set that is not how state works       
})

 useEffect(() => {
     console.log(abonnes)//this will log abonnes whenever abonnes value changes
  }, [abonnes])

سعيد
  • 1,547
  • 1
  • 14
  • 32
0
function EditAbonnes() { 

    let history = useHistory();
    const { id } = useParams();
    /* alert(id); */

    const [nom, setNom] = useState('')
    const [prenom, setPrenom] = useState('')
    const [courriel, setCourriel] = useState('')

     
    const [abonnes, setAbonnes] = useState({
        courriel: "",
        id_Abonnes: "",
        nom: "",
        prenom: ""
        
    });
         
    useEffect (()=>{loadAbonnes();}, []);

    const loadAbonnes = async () =>{

        const result = await Axios.get(`http://localhost:4000/api/getonea/${id}`)

        console.log(result.data);
        /* i have an array with one object on my console /*

        setAbonnes(result.data);
                     
        console.log(abonnes);
        /* abonnes is empty   /*
        
        console.log(abonnes.nom); 
        /*empty string /* 
        
    }

return(        );} export default EditAbonnes