SeoBomi
SeoBomi

Reputation: 39

useEffect is not called appropriate time, so useState in useEffect is not working

I wanna display realtime data array(JSON form) from the server.

function ServerTest(){
    var a  = new Array();
    const client = createClient();
    const queue = v4();

    var a  = new Array();
    var cl = new Array();
    const [valueA, setValueA]=useState(a)

    client.onConnect = function () {
        subscribe(client, 'admin', queue, (payload:any) => { 
            
            var c : any;
            var tmp: any
            a=payload.Conversations
            if(a!==null){
                a.map((item:any)=>{
                    cl.push(item.name)
                })
               
            }
            
        });
        
        publish(client, 'api', 'admin', queue, {});

    }
    client.activate();
    
    useEffect(()=>{
        setValueA(cl)
        console.log(valueA)
    },cl)
    
    return (         
    <div>A: {valueA} </div>
    )
}

export default ServerTest

In useEffect, console.log(valueA) is working but only setValueA(cl) is not working. I think it is because useEffect is not called when 'cl' is changing.

Upvotes: 1

Views: 77

Answers (1)

kkesley
kkesley

Reputation: 3406

The problem is React doesn't know that your cl variable has changed (because it's not a state)

Besides, you don't need cl in the first place.

Just wrap the initial connection in useEffect and call setValueA when you got the data.

function ServerTest(){    
    const queue = v4();
    const [valueA, setValueA]= useState()

    useEffect(() => {
        const client = createClient();
        client.onConnect = function () {
            subscribe(client, 'admin', queue, (payload:any) => { 
                if(payload.Conversations!==null){
                    setValueA(payload.Conversations.map((item:any)=>item.name))
                }
                
            });
            publish(client, 'api', 'admin', queue, {});
        }
        client.activate();
    }, [])
    
    return (         
    <div>A: {valueA} </div>
    )
}

Upvotes: 3

Related Questions