How to update a React/Recoil state array from web bluetooth subscription callbacks? - reactjs

I am new to using React and Recoil and want to display real-time charts (using D3) from data that is gathered in real-time using the Web Bluetooth API.
In a nutshell, after calling await myCharacteristic.startNotifications() and myCharacteristic.addEventListener('characteristicvaluechanged', handleNotifications), the handleNotifications callback is called each time a new value is notified from a Bluetooth device (see this example).
I am using hooks and tried to modify a recoil state from the callback (this was simplified to the extreme, I hope it is representative):
export const temperatureState = atom({
key: 'temperature',
default: 0
})
export function BluetoothControls() {
const setTemperature = useSetRecoilState(temperatureState);
const notify = async () => {
...
temperatureCharacteristic.addEventListener('characteristicvaluechanged', event => {
setTemperature(event.target.value.getInt16(0))
}
}
return <button onClick={nofity}/>Start notifications</button>
}
This work fine if I want to display the latest value somewhere in the app. However, I am interested in keeping the last few (let's say 10) values in a circular buffer to draw a D3 chart.
I tried something along the lines of:
export const temperatureListState = atom({
key: 'temperature-list',
default: []
})
export function BluetoothControls() {
const [temperatureList, setTemperatureList] = useRecoilState(temperatureListState);
const notify = async () => {
...
temperatureCharacteristic.addEventListener('characteristicvaluechanged', event => {
let temperatureListCopy = temperatureList.map(x => x);
temperatureListCopy.push(event.target.value.getInt16(0))
if (temperatureListCopy.length > 10)
temperatureListCopy.shift()
setTemperatureList(temperatureListCopy)
}
}
return <button onClick={nofity}/>Start notifications</button>
}
However, is is pretty clear that I am running into the issue described here where the function is using an old version of temperatureList that is captured during render. As a result, temperatureState is always empty and then replaced with a list of one element.
How to maintain a consistent list in a React state/Recoil atom that is updated from an external callback? I think this issue is a bit similar but I'd like to avoid using another extension like Recoil Nexus.

useSetRecoilState accepts an updater function as an argument with the value to be updated as the first parameter:
export function BluetoothControls() {
const setTemperatureList = useSetRecoilState(temperatureListState);
const notify = async () => {
...
temperatureCharacteristic.addEventListener('characteristicvaluechanged', event => {
setTemperatureList(t => {
let temperatureListCopy = t.map(x => x);
temperatureListCopy.push(event.target.value.getInt16(0))
if (temperatureListCopy.length > 10)
temperatureListCopy.shift()
return temperatureListCopy
})
}
}
return <button onClick={nofity}/>Start notifications</button>
}
This solves the issue as the updater function is only evaluated on events.

Related

react query returning empty object for data

I am trying to abstract away my react/tanstack query.
I have a custom hook like the following:
const useGamesApi = () => {
const upcomingGamesQuery = useQuery(
["upcoming", date],
async () => {
const ret = await apiGetUpcomingGames(date);
return ret;
},
{
onSuccess: (data) => {
setGames(data);
},
}
);
return {
games: upcomingGamesQuery,
};
};
export default useGamesApi;
I am trying to consume my API as follows:
const [games, setGames] = useState<Game[]>([]);
const gamesApi = useGamesApi();
useEffect(() => {
setGames(gamesApi.games.data);
}, []);
This leads to compilation errors and also the value of my games state variable remains an empty array, as if the useEffect never ran.
Basically I am trying to abstract away my react query to provide a simplified way of interacting with it for my components, whilst also giving it a chance to modify the parameter of the date, so that I can be able to set until which date I would like to query.
What would be the correct (compilation vise) and idiomatic way of doing this with react?
(note I am using this in a react native project, not sure if it counts.)
As per rules , You need to add all the variables used inside useEffect as dependency so that it reacts once the value is changed.
You don't really need useEffect for you scenario. It is used to cause side effects. simply do it like :
const games: Game[] = gamesApi?.games?.data;
const games: Game[] = gamesApi?.games?.data || []; // incase you need default value

How to re-render a component when a non state object is updated

I have an object which value updates and i would like to know if there is a way to re-render the component when my object value is updated.
I can't create a state object because the state won't be updated whenever the object is.
Using a ref is not a good idea(i think) since it does not cause a re-render when updated.
The said object is an instance of https://docs.kuzzle.io/sdk/js/7/core-classes/observer/introduction/
The observer class doesn't seem to play well with your use case since it's just sugar syntax to manage the updates with mutable objects. The documentation already has a section for React, and I suggest following that approach instead and using the SDK directly to retrieve the document by observing it.
You can implement this hook-observer pattern
import React, { useCallback, useEffect, useState } from "react";
import kuzzle from "./services/kuzzle";
const YourComponent = () => {
const [doc, setDoc] = useState({});
const initialize = useCallback(async () => {
await kuzzle.connect();
await kuzzle.realtime.subscribe(
"index",
"collection",
{ ids: ["document-id"] },
(notification) => {
if (notification.type !== "document" && notification.event !== "write")
return;
// getDocFromNotification will have logic to retrieve the doc from response
setDoc(getDocFromNotification(notification));
}
);
}, []);
useEffect(() => {
initialize();
return () => {
// clean up
if (kuzzle.connected) kuzzle.disconnect();
};
}, []);
return <div>{JSON.stringify(doc)}</div>;
};
useSyncExternalStore, a new React library hook, is what I believe to be the best choice.
StackBlitz TypeScript example
In your case, a simple store for "non state object" is made:
function createStore(initialState) {
const callbacks = new Set();
let state = initialState;
// subscribe
const subscribe = (cb) => {
callbacks.add(cb);
return () => callbacks.delete(cb);
};
// getSnapshot
const getSnapshot = () => state;
// setState
const setState = (fn) => {
state = fn(state);
callbacks.forEach((cb) => cb());
};
return { subscribe, getSnapshot, setState };
}
const store = createStore(initialPostData);
useSyncExternalStore handles the job when the update of "non state object" is performed:
const title = React.useSyncExternalStore(
store.subscribe,
() => store.getSnapshot().title
);
In the example updatePostDataStore function get fake json data from JSONPlaceholder:
async function updatePostDataStore(store) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${Math.floor(Math.random()*100)+1}`)
const postData = await response.json()
store.setState((prev)=>({...prev,...postData}));
};
My answer assumes that the object cannot for some reason be in React as state (too big, too slow, too whatever). In most cases that's probably a wrong assumption, but it can happen.
I can't create a state object because the state won't be updated whenever the object is
I assume you mean you can't put that object in a React state. We could however put something else in state whenever we want an update. It's the easiest way to trigger a render in React.
Write a function instead of accessing the object directly. That way you can intercept every call that modifies the object. If you can reliably run an observer function when the object changes, that would work too.
Whatever you do, you can't get around calling a function that does something like useState to trigger a render. And you'll have to call it in some way every time you're modifying the object.
const myObject = {};
let i = 0;
let updater = null;
function setMyObject(key, value) {
myObject[key] = value;
i++;
if (updater !== null) {
updater(i);
}
};
Change your code to access the object only with setMyObject(key, value).
You could then put that in a hook. For simplicity I'll assume there's just 1 such object ever on the page.
function useCustomUpdater() {
const [, setState] = useState(0);
useEffect(()=>{
updater = setState;
return () => {
updater = null;
}
}, [setState]);
}
function MyComponent() {
useCustomUpdater();
return <div>I re-render when that object changes</div>;
}
Similarly, as long as you have control over the code that interacts with this object, you could wrap every such call with a function that also schedules an update.
Then, as long as your code properly calls the function, your component will get re-rendered. The only additional state is a single integer.
The question currently lacks too much detail to give a good assessment whether my suggested approach makes sense. But it seems like a very simple way to achieve what you describe.
It would be interesting to get more information about what kind of object it is, how frequently it's updated, and in which scope it lives.

How to update the state with the latest fetched item with an interval callback function inside useEffect?

I'm quite new to the React-TS world and I have recently been playing with useState and useEffect hooks only basically.
I have the following functional component inside which I'd like to fetch N items the first time and then start a periodic function that fetches the last item from the response data, updating the current state.
const fetcher = async (url: string) => await axios.get(url).then((res: AxiosResponse) => res.data);
type AirflowData = {
value: number; // perc values from 0 to 1
timestamp: number; // UTC time
};
const ActionDetector: React.FC = () => {
const [alerts, setAlerts] = useState<AirflowData[]>([]);
useEffect(() => {
// Fetch the latest N alerts first
getAlerts(100);
// Then start fetching the last alert every N milliseconds
const interval = setInterval(() => getLatestAlert(), 1000);
// Clear interval
return () => {
clearInterval(interval);
};
}, []);
/**
* Return the alert data after fetching it.
* #param numAlerts number of the last N alerts to return
*/
const getAlerts = async (numAlerts: number) => {
const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
setAlerts(fetchedAlerts.slice(-numAlerts));
};
/**
* Return the latest alert data available.
*/
const getLatestAlert = async () => {
const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
const latestFetchedAlert = fetchedAlerts.slice(-1)[0];
const latestAlert = alerts.slice(-1)[0];
if (latestFetchedAlert && latestAlert && latestFetchedAlert.timestamp !== latestAlert.timestamp) {
// Append the alert only if different from the previous one
setAlerts([...alerts, latestFetchedAlert]);
}
};
console.log(alerts);
return <></>
}
export default ActionDetector
The problem with this approach is that latestAlert is always undefined and that is due, if I understood how React works under the hood correctly, to the initial state change re-rendering trigger. After getAlerts() is called and fires setAlerts(...), the component starts the re-rendering and so, since getLatestAlert() is called inside the useEffect only the first time (the first render), it always read alerts as the initialized empty array.
I don't know if this is the correct reason behind this, but how can I achieve what I'm trying to do the right way?
The fundamental issue is that when updating state based on existing state, you need to be sure you have the latest state information. Your getLatestAlerts function closes over the alerts constant that was in scope when it was created, so it only ever uses that version of the constant (not the updated one from a subsequent render). Your useEffect setInterval callback closes over the getLatestAlerts function that was in scope when it was created, and only ever uses that version of the function.
To be sure you have the latest state, use the callback version of the state setter instead of the constant:
const getLatestAlert = async () => {
const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
const latestFetchedAlert = fetchedAlerts.slice(-1)[0];
if (latestFetchedAlert) {
setAlerts(alerts => {
const latestAlert = alerts.slice(-1)[0];
if (latestFetchedAlert && latestAlert && latestFetchedAlert.timestamp !== latestAlert.timestamp) {
// Append the alert only if different from the previous one
alerts = [...alerts, latestFetchedAlert];
}
return alerts;
});
}
};
Purely as a side note, I wouldn't use the idiom you seem to be using to get the last item from an array, array.slice(-1)[0]. Instead, I'd either use array[array.length - 1], or use the at method which just achieved Stage 4 and will be in this year's spec (it's easily polyfilled for older environments).

Use Hooks within class that doesn't doesn't get rendered

I have a child class that returns some JSX (an ion-item) it uses a hook to control some ion-icons (using the hook like a state but only because I can use useEffect which is very handy).
I also have a Bluetooth class. This is home to all the important Bluetooth functions. The reason it is in its own class is because I need this code accessible everywhere in the app (including the list of devices (the ion-items mentioned above) it creates).
I do it like this:
const _Bluetooth = () => {
const [state, setState] = useState([]);
useEffect(() => {
addDevice();
}, [state]);
const devices: any[] = [];
const bluetoothInitialize = () => {
for (let i = 0; i < 5; i++) {
let a = {name: "test", mac: i.toString(), connected:false}
setState({found: [...state.found, a]});
}
}
const connect = (id) => {
console.log("connecting");
}
const addDevice = () => {
let d = state.found[state.found.length - 1]
devices.push(<BluetoothDeviceItem key={d.mac} mac={d.mac} name={d.name} onClick={(id) => connect(id)} connectingState={d.connected ? 'connected' : 'not_connected'}></BluetoothDeviceItem>);
}
return {
devices, bluetoothInitialize, connect
};
}
export default _Bluetooth;
I then create an instance of this class in another file which acts as a global file and then other files import this global file giving access to that one instance of the class:
import _Bluetooth from '../components/bluetooth/Bluetooth'
export const Bluetooth = _Bluetooth();
Unfortunately the _Bluetooth class doesn't work. Since I am using a hook, React expects the component to be rendered and therefore the component needs to return JSX. However I don't want it to return JSX but rather the accessible functions and variables.
Like I said above I am using these hooks more like states but only because of the useEffect function.
I could easily get this working by doing:
const state = {found: []}
and then directly pushing items to the array. This takes away my ability of using useEffect which makes my life a little bit easier but also cleans up the code a little bit.
Is it possible to use hooks without rendering the components / returning any JSX?

Convert class to functional component using hooks equivalent to shouldComponentUpdate and componentDidUpdate

I am new to hooks and I came across this example here: https://codesandbox.io/s/github/iamhosseindhv/notistack/tree/master/examples/redux-example which is a class component and I am trying to convert it to a functional with hooks. I can perfectly use it as it is but the reason is because I want to learn as well.
I tried to implement it with useEffect but I didnt had the desire effect as I still show only one time the notification and if I tried to create again a todo for example it didnt show up.
function Notifier(props) {
const { notifications, removeSnackbar } = props;
const { enqueueSnackbar } = useSnackbar();
const [displayed, setDisplayed] = useState([]);
function storeDisplayed(key) {
setDisplayed([...displayed, key]);
}
console.log(displayed)
notifications.forEach((notification) => {
setTimeout(() => {
// If notification already displayed, abort
if (displayed.indexOf(notification.key) >= 0) return;
// Display notification using notistack
enqueueSnackbar(notification.message, notification.options);
// Add notification's key to the local state
storeDisplayed(notification.key);
// Dispatch action to remove the notification from the redux store
removeSnackbar(notification.key);
}, 1);
});
return null;
}
I want to display a notification whenever I create or edit something.
Add dependancies array as second parameter to the useeffect
useEffect(() => {
//something
};
}, [props.friend.id]); // Only re-subscribe if props.friend.id changes
The solution to my implementation is the missing - undefined key, so what I did was to add the key in the redux store and pass it to the component props.
function Notifier(props) {
const { notifications, removeSnackbar } = props;
const { enqueueSnackbar } = useSnackbar();
const [displayed, setDisplayed] = useState([]);
function storeDisplayed(key) {
setDisplayed([...displayed, key]);
}
notifications.forEach((notification) => {
setTimeout(() => {
// If notification already displayed, abort
if (displayed.indexOf(notification.options.key) >= 0) return;
// Display notification using notistack
enqueueSnackbar(notification.message, notification.options);
// Add notification's key to the local state
storeDisplayed(notification.options.key);
// Dispatch action to remove the notification from the redux store
removeSnackbar(notification.options.key);
}, 1);
});
return null;
}

Resources