There are parts of my app that must work synchronously. I am using zustand. The problem is that zustand's setState function works asynchronously. Please let me know if there are any other libraries that support synchronous state changes or any tricks.
App.js (react example)
// in real
import create from 'zustand'
import logo from './logo.svg';
import React, { useEffect } from 'react';
const useStore = create(() => ({
counter: 0
}))
function App() {
const { counter } = useStore()
useEffect(() => {
console.log(counter) // output: 0
useStore.setState({ counter: counter + 1 })
console.log(counter) // output: 0
useStore.setState({ counter: counter + 1 })
console.log(counter) // output: 0
}, []);
return (
<div></div>
);
}
export default App;
// my hope
// ...
useEffect(() => {
console.log(counter) // output: 0
useStore.setState({ counter: counter + 1 })
console.log(counter) // output: 1
useStore.setState({ counter: counter + 1 })
console.log(counter) // output: 2
}, []);
// ...
The problem is in your counter definition.
const { counter } = useStore()
should be
const counter = useStore((state)=> state.counter)
Here's an example of how your code should look:
store:
const useStore = create(() => ({
counter: 0,
addOne: () =>
set((state) => ({
counter: state.counter +1
})),
}))
App:
function App() {
const counter = useStore((state)=> state.counter)
const addOne = useStore((state)=> state.addOne)
useEffect(() => {
let interval = setInterval(() => addOne(), 1000)
return () => clearInterval(interval)
}, [counter]);
return (
<div>{counter}</div>
);
}
I'm throwing the setInterval function in there so that it updates once every second. Using the counter state as a dependency for useEffect will cause the component to re-render every time the state is changed.