Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo reactive variable are not working when imported into another file! Why?

src/another_folder/reactiveVarInitializationFile.js import {makeVar} from "@apollo/client"

export const selectStore = makeVar('')

//my component

import {Select,Spin} from "antd"
import {selectStore} from "../../reactives/selectStore.RV"
import {useQuery} from "@apollo/client"
import FETCH_STORES from "../../queries/getStoresSelectSoreDPD"
export default function(){
    const {data}= useQuery(FETCH_STORES)
    const store = selectStore()
    const onChange=(val)=>{
        console.log(val)
        selectStore(val)
    }
    console.log(store)
    return(
    <>
        {!data?(<Spin/>):(
            <Select
                style={{width:"200px"}}
                placeholder="Select store" 
                onChange={onChange}>
                {data.currentUser.outlets.map(el=><Select.Option key={el.id} value={el.id}>{el.name} 
               </Select.Option>)}        
            </Select>
            
        )}
        <p>{store}</p>
    </>
    )
}

Problem is when I import selectStore into my component I can not get its value by selectStore() or modify the var by doing selectStore("new value")

Can anyone help me out please?

like image 959
notinsky Avatar asked Oct 28 '25 01:10

notinsky


2 Answers

If using the reactiveVar directly it WILL NOT update when the value changes, it'll only update on initial render.

HOWEVER, if you want it to update when the value changes and trigger a re-render, you need to use the useReactiveVar hook: https://www.apollographql.com/docs/react/local-state/reactive-variables/

So, something like this:

const store = useReactiveVar(selectStore);
like image 57
Bryce Avatar answered Oct 30 '25 19:10

Bryce


THIS ANSWER IS OUTDATED SINCE useReactiveVar IS UP

Reactive variables need to be consumed inside a query if you want a re-render. Here is the official documentation about it:

As their name suggests, reactive variables can trigger reactive changes in your application. Whenever you modify the value of a reactive variable, queries that depend on that variable refresh, and your application's UI updates accordingly.

So you need to write a read policy for selecStore field. Then use this field in the query like this:

 const { data } = useQuery(gql`
   query GetSelectStore {
    selectStore @client
  }
 `);
like image 22
Erkin Kurt Avatar answered Oct 30 '25 19:10

Erkin Kurt