Search code examples
reactjsleafletreact-leaflet

React useEffect is late runnig


I have a state map. map contains coordinates and goes to react-leaflet as props. I am updating the map using useEffect, but it works late, the inital value is gone as props.

const [map,setMap] = useState([0,0]);

useEffect(() => {
  const data = getIp();
  data.then(result => {
    setMap([result.lat,result.lon]);
  })
},[])

console.log(map);

console.log view:

Array [ 0, 0 ]
Array [ 36.8943, 30.7209 ]

Solution

  • useEffect hook is running after the first render so if you want to avoid the first render you could use a loader in your state and use it to conditionally render the content:

    const [loading, setLoading] = useState(true);
    
    const [map,setMap] = useState([0,0]);
    
    useEffect(() => {
      const data = getIp();
      data.then(result => {
        setMap([result.lat,result.lon]);
        setLoading(false);
      })
    },[])
    
    if (loading) return <p>Loading</p>;
    
    return (
        ...your code
    );