ReactJS: useEffect update metadata on every request of aws IVS chaannel - reactjs

I would like to perform the continuous process as this below link to update the metadata of the aws IVS stream.
I have managed with the useEffect hook but it is not updating the value and throws the undefined error.
https://codepen.io/amazon-ivs/pen/XWmjEKN?editors=0011
function AppComponent(props) {
const [metaData, setMetaData] = useState(null)
useEffect(() => {
const data = props.metadata
const initData = async () => {
setMetaData(data)
}
initData()
}, [metaData])
return (
<div>
<h2>{metaData.question}</h2>
</div>
)
}

Ok, I am a bit confused about this code snippet.
if you assume that you receive in your props metadata then probably you don't need state at all, and your code should look like below
function AppComponent(props) {
return (
<div>
<h2>{props.metadata.question}</h2>
</div>
)
}
Regarding your code overall, you have created metaData with initial value null, so metaData.question will throw error on the initial run.
It doesn't make no sense to run setMetaData asynchronously. Also you have subscribed to metaData change in your hook, but only place where you update it is your hook, it will cause also infinite loop.
It would be better if you will provide more information about your issue and make this question not so wide
If you use only some properties from the object you are passing then you probably don't need to pass whole object as a prop, but it would be better to pass props that you use, as any change on the object, you are passing will cause rerendering of the component. Also you can try to use React.memo to avoid unnecessary rerendering cycles.

Related

Use React props as a function argument

I want to check if this is good practice, and if there's a better approach to it. I have a function that is called when the component loads and when clicking on a couple of buttons, so I need to use it inside useEffect, and pass it to other components. I could use useCallback, but I don't see how this approach is not enough, since the components that can call getWeatherHere also need isCelsius, thus being able to use it as argument (the argument and the state are the same).
export default function weatherInfo() {
const [weatherInfo, setWeatherInfo]: [IWeather, React.Dispatch<IWeather>] = useState();
const [isCelsius, setIsCelsius] = useState(true);
function getWeatherHere(isCelsius: boolean) {
navigator.geolocation.getCurrentPosition(async ({coords: {latitude, longitude}}) => {
const data = await Weather.getWeather(latitude, longitude, !isCelsius ? 'imperial' : undefined);
setWeatherInfo(data);
});
}
useEffect(() => {
getWeatherHere(isCelsius);
}, [isCelsius]);
return (
<OtherComponent isCelsius={isCelsius} getWeatherHere={getWeatherHere}/>
);
}
This is how you do it, but there are tools available to make this easier.
Consider using a construction like useAsync from react-use. It allows you to express a Promise as a state. This avoids all sort of pitfalls and issues of using Promises in functional Components.
So you get something like:
const state = useAsync(async () => {
const { coords: { latitude, longitude } } = await navigator.geolocation.getCurrentPosition();
return {
isCelsius: isCelsius,
data: await Weather.getWeather(latitude, longitude, !isCelsius ? 'imperial' : undefined),
};
}, [ isCelsius ]);
return <>
{state.loading === false && <OtherComponent
isCelsius={state.value.isCelsius}
weatherHere={state.value.data}
/>
</>;
Some remarks:
I added isCelsius to the value of the async state. If you don't do that, and pass isCelsius directly, you're going to have a desynch between the value of isCelsius and the weather data. I would actually expect that the temperature unit is part of the result of the getWeather request, but if it's not, this works.
There is one problem when using promises with setState in React, and that has to do with cleanups. If your Component is unmounted before the promise is completed, it doesn't magically cancel the code. It will finish the request and call setWeatherInfo. That will trigger a re-render on an unmounted component, which React will give you a warning about. It's not a huge problem in this case, but it can become a problem in more complex situations. useAsync takes care of this by checking if the component is still mounted at the end of the fetcher function. You can also do that yourself by using usePromise, but I would try to avoid using Promises in this way all together.
Your code can suffer from race conditions. If you change isCelsius quickly a couple of times, it's going to be a coinflip which result is going to end up being used. useAsync also takes care of this.
If, instead of passing the weather, you want to pass a function that fetches the weather, use useAsyncFn instead. The state is the same, but it also returns a function that allows you to call the fetcher function. This is in addition to the value of isCelsius changing.
As your post is about best practices, I'll let you my 2 cents.
Some things that I would change using only pure react to refactor it.
export default function weatherInfo() {
// You don't need to type both returns, only the hook.
const [weatherInfo, setWeatherInfo] = useState<IWeather | undefined>(undefined);
// Why do you need this state if it's not changing?
// May you can put this in a const and save one state.
const isCelsius = true;
// I may change this "Here" in the function, because it don't look wrong, by it's subjective
// Use "ByUserLocation" it's a better description
// With the hook useCallback you can rerender the function only based on the right values
const getWeatherByUserLocation = useCallback(() => {
// Extracting the function improves the maintenance by splitting each step of the process and each callback function.
const callbackFn = async ({coords: {latitude, longitude}}) => {
// Turn your validations into variables with a well-descriptive name.
// Avoid making validation starting by negating the value;
const temperatureUnit = isCelsius ? 'celsius' : 'imperial';
// Avoid using "data" as the name of a variable even when it looks clear what the data is. In the future, you will not remember if this logic should change.
const weatherInfoData = await Weather.getWeather(
latitude,
longitude,
temperatureUnit
);
setWeatherInfo(weatherInfoData);
};
navigator.geolocation.getCurrentPosition(callbackFn);
}, [isCelsius]);
useEffect(() => {
getWeatherByUserLocation();
// removing the prop from the function, you avoid calling it many times based on the state change
// A useEffect without dependencies on the dependency array, it will only be called on the component mount and unmount
}, []);
return (
<OtherComponent isCelsius={isCelsius} getWeatherByUserLocation={getWeatherByUserLocation}/>
);
}

React - issue with useEffect() and axios.get

I am struggling to understand why my code is not working. I am using the useEffect() hook to make a call to an API, and then I am using setState() to update my component state. In my JSX, I am mapping my info array to render the data.
Here's my code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [info, setInfo] = useState();
console.log(info);
useEffect(() => {
const getUsers = async () => {
const res = await axios('https://api.mocki.io/v1/b043df5a');
console.log(res.data);
setInfo(res.data);
};
getUsers();
}, []);
return (
<div>
<input type='text' placeholder='Search users' />
<input type='text' placeholder='Search users' />
{info.map((el, index) => {
console.log(el);
return <h1 key={index}>{el.city}</h1>;
})}
</div>
);
}
export default App;
However, I get this error: 'TypeError: Cannot read property 'map' of undefined'. My best guess is that my JSX is rendered before my state is populated with API info.
The code does work when I write the following JSX, which allows me to check if 'info' is true:
{info && info.map((el, index) => {
console.log(el);
return <h1 key={index}>{el.city}</h1>;
})}
Is this a normal behavior? Why is useEffect not populating my state before my page is rendered?
I would appreciate your help, as I am struggling to find the solution to this specific issue.
Thanks!
Just do this:
const [info, setInfo] = useState([]);
The issue is that you have no intial value and therefore it automatically defaults to undefined. Now you are trying to call .map on a value that is undefined therefore it throws an error. With an empty array as the initial value however, .map will loop over an empty array on the first render (before the useEffect) and it won't throw any error.
that's because useEffect hook will run after the dom render phase finished and one more thing that can cause the delay of getting data is the fact that you're calling an asynchronous function which usually get some time to finished.
so what are the possible options here:
just use empty array [] as default value
check the length of the state like info.length && whatever...
sometimes you can use the useLayoutEffect which is kinda a synchronous operation. but in your case which is an api calls solution 1 and 2 is the answer
You are trying to iterate over undefined it's normal cause you need to check first before data will come to your state. You can achieve this in two ways:
info && info.map
But your initial state must be falsy value like:
useState(null)
Or better way to set initial state to empty array and map will run when data will come and you will get no error.
So basicly useEffect function is equivalent of componentDidMount. What I'm trying to say your component renders and then it executes function passed in useEffect. To avoid this eighter use check that you introduced as a fix yourself or pass default value to useState method. I would suggest your option but with condition if info exists show it and if it's not then show some kind of loading indicator.
A use Effect with a [] as second can be interpreted as a 'componentDidMount'
To give a very simple answer, your code is 'executed' the first time without the useEffect. So indeed, 'info' will not exist. At this point your 'info' variable is not yet defined. Then, when your component 'is mounted', it will execute the code in your useEffect. Only then info will be filled in.
I would recommend to go through this documentation to fully understand this: https://reactjs.org/docs/state-and-lifecycle.html

Do I have to worry about useState causing a re-render?

NB: I've asked this on wordpress.stackexchange, but it's not getting any response there, so trying here.
I'm not sure if this is WordPress specific, WordPress's overloaded React specific, or just React, but I'm creating a new block plugin for WordPress, and if I use useState in its edit function, the page is re-rendered, even if I never call the setter function.
import { useState } from '#wordpress/element';
export default function MyEdit( props ) {
const {
attributes: {
anAttribute
},
setAttributes,
} = props;
const [ isValidating, setIsValidating ] = useState( false );
const post_id = wp.data.select("core/editor").getCurrentPostId();
console.log('Post ID is ', post_id);
const MyPlaceholder = () => {
return(
<div>this is a test</div>
);
};
const Component = MyPlaceholder;
return <Component />;
}
If I comment out const [ isValidating, setIsValidating ] = useState( false ); then that console.log happens once. If I leave it in, it happens twice; even if I never check the value of isValidating, never mind calling setIsValidating. I don't want to over-optimize things, but, equally, if I use this block n times on a page, the page is getting rendered 2n times. It's only on the admin side of things, because it's in the edit, so maybe not a big deal, but ... it doesn't seem right. Is this expected behavior for useState? Am I doing something wrong? Do I have to worry about it (from a speed perspective, from a potential race conditions as everything is re-rendered multiple times)?
In your example code, the console.log statement is being immediately evaluated each time and triggering the redraw/re-rendering of your block. Once console.log is removed, only the state changes will trigger re-rendering.
As the Gutenberg Editor is based on Redux, if the state changes, any components that rely on that state are re-rendered. When a block is selected in the Editor, the selected block is rendered synchronously while all other blocks in the Editor are rendered asynchronously. The WordPress Gutenberg developers are aware of re-rendering being a performance concern and have taken steps to reduce re-rendering.
When requesting data from wp.data, useEffect() should be used to safely await asynchronous data:
import { useState, useEffect } from '#wordpress/element';
export default function MyEdit(props) {
...
const [curPostId, setCurPostId] = useState(false);
useEffect(() => {
async function getMyPostId() {
const post_id = await wp.data.select("core/editor").getCurrentPostId();
setCurPostId(post_id);
}
getMyPostId();
}, []); // Run once
const MyPlaceholder = () => {
return (
<div>Current Post Id: {curPostId}</div>
);
};
const Component = MyPlaceholder;
return <Component />;
}
As mentioned in the question, useState() is used in core blocks for setting and updating state. The state hook was introducted in React 16.8, its a fairly recent change and you may come across older Gutenberg code example that set state via the class constructor and don't use hooks.
Yes, you have to worry about always put an array of dependencies, so that, it won't re-render, As per your query, let's say are planning to edit a field here is the sample code
const [edit, setEdit]= useState(props);
useEffect(() => {
// logic here
},[edit])
that [edit] will check if there is any changes , and according to that it will update the DOM, if you don't put any [](array of dependencies) it will always go an infinite loop,
I guess this is expected behavior. If I add a similar console.log to native core blocks that use useState, I get the same effect. It seems that WordPress operates with use strict, and according to this answer, React double-invokes a number of things when in strict mode.

does `useCallback` have something like a `useRef.current` inside it that will ensure that calls always use the latest version of the callback?

I have a situation where I am loading several datasets; the user can choose how many to load. All the datasets are rendered on the same chart. The datasets load individually and asynchronously.
The code is something along the lines of
export const DatasetGraph = ({userSelections}) => {
const [datasets, setDatasets] = useState({});
// when a selection changes, update the data
useEffect(() => {
// while loading a dataset, it is visible but has no data
setDatasets(userSelections.map(selec => ({ dsname: [] })));
// trigger asynchronous loads for each new dataset
userSelections.forEach((dsname) => fetchDataset(dsname));
}, [userSelections]);
const fetchDataset = async (dsname) => {
response = await fetch(url + dsname);
// QUESTION: after the await, will this call the most recent version of
// the callback? Will it use the most recent datasets object or an old
// one saved in the useCallback closure?
updateDataset(dsname, response);
};
// when a fetch returns, update the empty placeholder with the real data
const updateDataset = useCallback(
// For this toy example, we could use a setState function to always
// retrieve the latest `datasets`. However, this callback may use other
// state which is really what this question is about.
(dsname, response) => setDatasets({ ...datasets, dsname: response }),
[datasets]
);
return <Graph data={datasets}></Graph>;
};
I have not yet tried just having each dataset be a React component that doesn't render anything to the DOM, which can then manage its own loading state. That might actually be easier.
useCallback uses the dependencies array to detect changes
The useCallback method uses the dependencies array you pass to it in order to memoize the value of your function. Your function will be recreated every time but not assigned to updateDataset unless one of the dependencies has changed.
You should be wary of using useCallback unless a component below your function is expensive to rerender, otherwise, useCallback won't have much of a positive effect on your application's performance if any positive effect at all.
It works the same way that useMemo does to ensure that your data, in the case of useCallback it is a function, is only updated on your variable when something it depends on has changed.

When updating state from props, why useEffect() instead of checking directly in the component?

When updating state when props change, the commonly held approach is to use useEffect() with the prop as a dependency:
const Component = ({prop}) => {
const [state, setState] = useState(prop);
useEffect(() => {
setState(prop);
}, [prop]);
return <div>{state}</div>;
}
I have to wonder, is there an advantage to this over doing a comparison directly in the component itself, like so:
const Component = ({prop}) => {
const [state, setState] = useState(prop);
if (prop !== state) {
setState(prop);
}
return <div>{state}</div>;
}
It looks like both approaches cause the component to execute twice -- once with the prop and state out of sync, once in sync -- but the second approach looks like it avoids adding a hook to the stack. It also looks like it could be optimized out of the DOM reconciliation, since it doesn't have to wait for the DOM to be generated the way useEffect() does. I'm not even sure it is easier to read, other than being "The Hooks Way."
Does anyone have an idea why the useEffect() route could be better than the inline check?
The official React docs use the second approach for syncing props to state:
https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops
function ScrollView({row}) {
const [isScrollingDown, setIsScrollingDown] = useState(false);
const [prevRow, setPrevRow] = useState(null);
if (row !== prevRow) {
// Row changed since last render. Update isScrollingDown.
setIsScrollingDown(prevRow !== null && row > prevRow);
setPrevRow(row);
}
return `Scrolling down: ${isScrollingDown}`;
}
The difference between updating state in useEffect and updating state during render is that, useEffect is called after React already commits the updates, i.e. the updates would be reflected in DOM, then you'll update state which will update the DOM again. The second way causes a re-render, but there's only one commit to the DOM.
I think it's important to understand when to use hooks and when not too.
The answer to this question is a very helpful How does React implement hooks so that they rely on call order.
We have recently discovered a lot of problems to do with the useEffect hook, one of them being
useEffect(() => {
// Called on first render and every props.foo update
}, [props.foo])
We didn't want it to be called on the first render only on every update.
Another on being useEffect gives warning when using objects & arrays, instead of a value.
I'm not saying don't use the useEffect ever I love the useEffect hook, but instead of saying why shouldn't use it. You should say do I need useEffect to get what I need to achieve.
For your example unless you are setting the state at another point I would suggest. Just using the prop. If you are setting the state I would have a look at the above link at the schema found.
The schema of a single hook is as below. It can be found in the implementation
function createHook(): Hook {
return {
memoizedState: null,
baseState: null,
queue: null,
baseUpdate: null,
next: null,
};
}
Think do I need to make use of the hooks queue when setting the state, if not then don't use a hook.
Another good use of the hook is are you going to be putting multiple values in the hook array if so it's a good idea to use it then!
Hope that helps :)

Resources