Get state and update state in a non react component in nextjs

Viewed 438

I am working on a nextjs project where i have a helpers folder in level with pages folder.

I have a ts file inside helpers folder and here i want to get the latest state and update state depending on the latest state

This is how im getting the state

store().getState()

where store is imported from store.js

Im updating state depending on the previous state

    const state = store().getState()

    if(!state.currentUser){   // here im checking if state has currentUser
        store().dispatch(Action)  // here im calling action which will update the state
    }

    do further operations

The problem here is I'm not getting the updated state from store().getState() after updating the state. Is the way I'm managing things correctly? How to get the updated state?

*EDIT* : Im sending a helper function as a prop to many if my page components. Now that i dont want to touch this , i somehow want to get the updated state and dispatch actions based on the state itself. Note that the hepler function is not a functional component

Thanks in advance

1 Answers

The problem is that this store you're using isn't part of React, so React doesn't know when the data changes. You have to create a way to let React know that the data changes so it could then rerender your component or trigger an action. Does your store offer a way to subscribe to changes? If so you can do something like this in your component (assuming you're using hooks):

Edit: Reusable hook way:

export const useStore = () => {
    const [storeState, setStoreState] = useState(store().getState());
    useEffect(() => {
      const subscribeFunc = (newState) => setStoreState(newState));
      store().subscribe(subscribeFunc);
      return () => {
        store().unsubscribe(subscribeFunc);
      }
    }, [])

    return [storeState, store().dispatch]
  }

then in your component

const [storeState, dispatch] = useStore();

// listen to changes of the currentUser and fire actions accordingly
useEffect(() => {
  if (!storeState.currentUser) {
    dispatch(Action)
  }
}, [storeState.currentUser])

Initial way:

// sync the store state with React state
const [storeState, setStoreState] = useState(store().getState());
useEffect(() => {
  const subscribeFunc = (newState) => setStoreState(newState));
  store().subscribe(subscribeFunc);
  return () => {
    store().unsubscribe(subscribeFunc);
  }
}, [])

// listen to changes of the currentUser and fire actions accordingly
useEffect(() => {
  if (!storeState.currentUser) {
    store().dispatch(Action)
  }
}, [storeState.currentUser])

By setting the state in the component on change, React now knows that data changed and will act accordingly.

This is a very local approach to explain the concept, but it would obviously be better to create a reusable hook to use throughout your app for any store.

Related