1

enter image description here

const [data, setData] = useState(null)

    useEffect(()=>{
        setData({id:1, title:"hello world"})
    },[])

    useEffect(()=>{
        
        //why data value is null?
        Echo.join('ChatMessage').listen('ChatMessage',(res) => console. log (data))

        //
        Echo.join('ChatMessage').listen('ChatMessage',(res) => setData (oldData => {
            console.log(oldData) // {id:1, title:"hello world"}
            return oldData
        }))

    },[])

How can I call the state value of the changed data?

The existing state can only be called by using the set function. Is there any way to call it easily?

MOON LEE
  • 11
  • 1

1 Answers1

0

useState is asynchronous to update.

Your setting the state inside a useEffect hook with no dependencies at the same time as trying to call and access it. As such, the value will not be reflected at the same time.

As you are effectively trying to set default state why don't you use the defaultValue of the useState hook to set it?

const {useState, useEffect} = React;
const Example = ({title}) => {
    const [data, setData] = useState({id:1, title:"hello world"})
    useEffect(()=>{  
        console.log(data);  
    },[])
        return (
            <div>
            </div>
        );
    };

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <Example />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
DanielJ
  • 729
  • 2
  • 7
  • 26
  • I'm not sure if I've expressed what I'm asking about correctly. When I receive a message with Echo.listen, I want to load the changed state, but only the initial state is called. Is there any way to retrieve the changed state? – MOON LEE Nov 19 '22 at 04:46