I have an input. On every change to the input, I want to call an API.
Here's a simplified version of the code:
// updated by input
const [urlText, setUrlText] = useState("");
const fetcher = useFetcher();
useEffect(() => {
if (urlText === "" || !fetcher) return;
fetcher.load(`/api/preview?url=${urlText}`);
}, [urlText]);
The issue is, when I put urlText inside of the dependencies array, there is an infinite rendering loop, and React claims the issue is I might be updating state inside of the useEffect. However, as far as I can tell, I'm not updating any state inside of the hook, so I'm not sure why an infinite re-render is happening.
Any thoughts?
The fuller version of the code is:
Note: The bug still happens without the debounce, or the useMemo, all of that stuff is roughly irrelevant.
export default function () {
const { code, higlightedCode } = useLoaderData<API>();
const [urlText, setUrlText] = useState("");
const url = useMemo(() => getURL(prefixWithHttps(urlText)), [urlText]);
const debouncedUrl = useDebounce(url, 250);
const fetcher = useFetcher();
useEffect(() => {
if (url === null || !fetcher) return;
fetcher.load(`/api/preview?url=${encodeURIComponent(url.toString())}`);
}, [debouncedUrl]);
return (
<input
type="text"
placeholder="Paste URL"
className={clsx(
"w-full rounded-sm bg-gray-800 text-white text-center placeholder:text-white"
//"placeholder:text-left text-left"
)}
value={urlText}
onChange={(e) => setUrlText(e.target.value)}
></input>
);
}
The problem you're having is that fetcher is updated throughout the fetch process. This is causing your effect to re-run, and since you are calling load again, it is repeating the cycle.
You should be checking fetcher.state to see when to fetch.
useEffect(() => {
// check to see if you haven't fetched yet
// and we haven't received the data
if (fetcher.state === 'idle' && !fetcher.data) {
fetcher.load(url)
}
}, [url, fetcher.state, fetcher.data])
https://remix.run/docs/en/v1/api/remix#usefetcher
You might by setting state in useFetcher hook, please check code of load method from useFetcher.
Update: I'm silly. useDebounce returns an array.
Related
The problem: I have a FlashList that uses React Context to fill in the data (the data is an array of objects that renders a View) but when I update the context and the extraData prop for FlashList, the list does not re-render, or re-renders sometimes, or takes multiple events to actually re-render.
The Code:
// Many imports, they are all fine though
export default () => {
// Relevant context.
const {
cardsArray,
cardsArrayFiltered,
updateCardsArray,
updateCardsArrayFiltered
} = useContext(AppContext);
// Relevant state.
const [didUpdateCards, setDidUpdateCards] = useState(false);
const [cardsFilters, setCardsFilters] = useState([]);
// Relevant refs.
const flatListRef = useRef(null);
// Example effect on mount
useEffect(() => {
setInitialAppState();
}, []);
// Effect that listen to changing on some data that update the context again
useEffect(() => {
const newCardsArray = doSomeFiltering(cardsArray, cardsFilters);
updateCardsArrayFiltered(newCardsArray);
setDidUpdateCards(!didUpdateCards);
}, [cardsFilters]);
// Example of promisey function that sets the initial context.
const setInitialAppState = async () => {
try {
const newCardsArray = await getPromiseyCards();
updateCardsArrayFiltered(newCardsArray);
updateCardsArray(newCardsArray);
} catch ( err ) {
console.debug( err );
}
}
// Renderer for the list item.
const renderListItem = useCallback((list) => <Card key={list.index} card={list.item} />, []);
// List key extractor.
const listKeyExtractor = useCallback((item) => item.id, []);
return (
<FlashList
ref={flatListRef}
data={cardsArrayFiltered}
extraData={didUpdateCards}
keyExtractor={listKeyExtractor}
renderItem={renderListItem}
showsVerticalScrollIndicator={false}
estimatedItemSize={Layout.window.height}
/>
);
}
Notes:
What I did not write all out is the function, logic, view to update cardsFilters however the above effect IS running when it changes.
Moreover, this line here, const newCardsArray = doSomeFiltering(cardsArray, cardsFilters); does indeed return the proper updated data.
What's going on here? I am updating the extraData prop with that didUpdateCards state when the context changes which I thought was the requirement to re-render a FlatList/FlashList.
It looks like object being passed as extraData is a boolean. This means that if the previous value was true, setting it as true again wouldn't count as a change. Instead use an object and update it when you want list to update.
To try just set extraData={{}}. if everything works as expected it means that your update logic has some problem.
This question already has answers here:
State not updating when using React state hook within setInterval
(14 answers)
Closed 5 months ago.
I'm working on building a file upload portal in React that allows for multiple concurrent uploads, using an amalgamation of some preexisting code and new code that I'm writing myself. The code base is pretty complex, so I will explain what's happening at a high level, illustrate the problem, and then provide a toy example to simulate what's happening in CodeSandbox.
The top level component has a files state variable from useState, which is an object that contains sub objects with information regarding each file that the user is currently uploading, that is being mapped across in the JSX and returning UI elements for each. Think:
const uploadData = {
1: {
id: 1,
name: "File 1",
progress: 0
},
2: {
id: 2,
name: "File 2",
progress: 0
}
};
const [files, setFiles] = useState(uploadData);
const progressElements = Object.values(files).map((file) => (
<Progress key={file.id} value={file.progress} />
))
When an upload is initiated, existing code dictates that a callback is provided from the top level that receives an updated progress value for a given upload, and then sets that into state in files for the corresponding upload. This works perfectly fine when there is only one active upload, but as soon as a second file is added, the fact that the same files state object is being concurrently updated in multiple places at once bugs out the UI and causes the rendered JSX to be inaccurate. What is the correct way to handle concurrent updates to the same state at once?
Below is a super simplified (and hastily written, my apologies) sandbox as a toy example of what's going on. It's obviously not an exact replica of what's happening in the actual code, but it gets the general idea across. You can see that, with one upload going, the UI updates fine. But when additional uploads are added, any updates to the first overwrite the existence of the new upload in state and thus break the UI.
https://codesandbox.io/s/elastic-wozniak-yvbfo6?file=/src/App.js:133-297
const { useState, useEffect } = React;
const App = () => {
const uploadData = {
1: {
id: 1,
name: "File 1",
progress: 0
}
};
const [files, setFiles] = useState(uploadData);
const [uploading, setUploading] = useState(false);
const updateProgress = (uploadId, progress) => {
setFiles({
...files,
[uploadId]: {
...files[uploadId],
progress
}
});
};
const filesArray = Object.values(files);
const addNewFile = () => {
const lastUpload = files[filesArray.length];
const newId = lastUpload.id + 1;
setFiles({
...files,
[newId]: {
id: newId,
name: 'File ' + newId,
progress: 0
}
});
};
return (
<div className="App">
{filesArray.map((file) => (
<UploadStatus
key={file.id}
uploading={uploading}
setUploading={setUploading}
file={file}
updateProgress={updateProgress}
/>
))}
<button
onClick={
uploading ? () => setUploading(false) : () => setUploading(true)
}
>
{uploading ? "Cancel Upload" : "Start Upload"}
</button>
{uploading && <button onClick={addNewFile}>Add New File</button>}
</div>
);
}
const UploadStatus = ({
file,
updateProgress,
uploading,
setUploading
}) => {
useEffect(() => {
if (!uploading) return;
let calls = 0;
const interval = setInterval(() => {
calls++;
updateProgress(file.id, calls * 10);
}, 1000);
if (calls === 10) {
clearInterval(interval);
setUploading(false);
}
return () => clearInterval(interval);
}, [uploading]);
return (
<div key={file.id}>
<p>{file.name}</p>
<progress value={file.progress} max="100" />
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.production.min.js"></script>
<body>
<div id="root"></div>
</body>
Any help or thoughts would be greatly appreciated. Thanks!
Based on what is inside your codesandbox - the issue is just with closures and missing items in dependency array of useEffect. I do understand why you want to have only the things you described in depsArray of useEffect - but if you dont provide all the things there - you will get an issue with closure and you will be calling the old function or refering old variable, what is happening in your codesandbox. Consider wrapping everything that is passed to the hooks or child components with useMemo, useCallback and other memoizing functions react provide and include everything that is needed in depsArray. There is a workaround with useRef hook to hold a reference to the specific function you want to call + useEffect with the only purpose to update this useRef variable.
So rough fix 1:
import { useEffect, useRef } from "react";
export default function UploadStatus({
file,
updateProgress,
uploading,
setUploading
}) {
const updateProgressRef = useRef(updateProgress);
const setUploadingRef = useRef(setUploading);
useEffect(() => {
updateProgressRef.current = updateProgress;
}, [updateProgress]);
useEffect(() => {
setUploadingRef.current = setUploading;
}, [setUploading]);
useEffect(() => {
if (!uploading) return;
let calls = 0;
const interval = setInterval(() => {
calls++;
updateProgressRef.current(file.id, calls * 10);
if (calls === 10) {
clearInterval(interval);
setUploadingRef.current(false);
}
}, 1000);
return () => clearInterval(interval);
}, [file.id, uploading]);
return (
<div key={file.id}>
<p>{file.name}</p>
<progress value={file.progress} max="100" />
</div>
);
}
You will have to fix some logic here due to when any of the Uploadings is done - all the rest uploading will "stop" due to uploading and setUploading parameters.
What can simplify the fixing process is to modify addNewFile and updateProgress so they will not rely on closure captured files. setXXX functions from useState can recieve either the new value as a parameter, either a callback currentValue => newValue. So you can use callback one:
So rough fix 2:
const updateProgress = (uploadId, progress) => {
setFiles((files) => ({
...files,
[uploadId]: {
...files[uploadId],
progress
}
}));
};
const addNewFile = () => {
const lastUpload = files[filesArray.length];
const newId = lastUpload.id + 1;
setFiles((files) => ({
...files,
[newId]: {
id: newId,
name: `File ${newId}`,
progress: 0
}
}));
};
This fix will actually work better but still, wirings of states and components and depsArray should be fixed more precisiolly.
Hope that helps you to get the basic idea of what is going on and in which direction to dig with your issues.
I have my react js app linked to cloud Firestore and I'm trying to display the objects on my js file.
I have only 1 object in my Firestore but it keeps reading in a loop and i cant figure out why.
Code from explore.js (display objects from Firebase)
const [nft,setNft]=useState([])
const getNft= async()=>{
const nft = await fs.collection('NFT').get();
const nftArray=[];
for (var snap of nft.docs){
var data = snap.data()
data.ID = snap.id;
nftArray.push({
...data
})
if(nftArray.length===nft.docs.length){
setNft(nftArray);
}
}
}
useEffect(()=>{
getNft();
})}
{nft.length > 0 && (
<div>
<div className='cardContainer'>
<Nft nft={nft}/>
</div>
</div>
)}
{nft.length < 1 && (
<div className='loading'>Loading products..</div>
)}
Infinite loop console
useEffect has a "trigger" property.
ex:
Will run on every render
useEffect(() => {
//do something
});
Will run only once
useEffect(() => {
//do something
}, []);
Will run when given properties changes
useEffect(() => {
//do something
}, [someProperty, someOtherProperty]);
In your case, you are calling the async function, the async function updates the state, and causes a rerender. Since you don't have any trigger (or empty array) added to the useEffect, it will run again, and again, and again.
I have a custom hook in my React application which uses a GET request to fetch some data from the MongoDB Database. In one of my components, I'm reusing the hook twice, each using different functions that make asynchronous API calls.
While I was looking at the database logs, I realized each of my GET requests were being called twice instead of once. As in, each of my hooks were called twice, making the number of API calls to be four instead of two. I'm not sure why that happens; I'm guessing the async calls result in re-renders that aren't concurrent, or there's somewhere in my component which is causing the re-render; not sure.
Here's what shows up on my MongoDB logs when I load a component:
I've tried passing an empty array to limit the amount of time it runs, however that prevents fetching on reload. Is there a way to adjust the custom hook to have the API call run only once for each hook?
Here is the custom hook which I'm using:
const useFetchMongoField = (user, id, fetchFunction) => {
const [hasFetched, setHasFetched] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
if (!user) return;
try {
let result = await fetchFunction(user.email, id);
setData(result);
setHasFetched(true);
} catch (error) {
setError(error.message);
}
};
if (data === null) {
fetchData();
}
}, [user, id, fetchFunction, data]);
return { data, hasFetched, error };
};
This is one of the components where I'm re-using the custom hook twice. In this example, getPercentageRead and getNotes are the functions that are being called twice on MongoDB (two getPercentageRead calls and two getNotes calls), even though I tend to use each of them once.
const Book = ({ location }) => {
const { user } = useAuth0();
const isbn = queryString.parse(location.search).id;
const { data: book, hasFetched: fetchedBook } = useFetchGoogleBook(isbn);
const { data: read, hasFetched: fetchedPercentageRead } = useFetchMongoField(
user,
isbn,
getPercentageRead
);
const { data: notes, hasFetched: fetchedNotes } = useFetchMongoField(
user,
isbn,
getNotes
);
if (isbn === null) {
return <RedirectHome />;
}
return (
<Layout>
<Header header="Book" subheader="In your library" />
{fetchedBook && fetchedPercentageRead && (
<BookContainer
cover={book.cover}
title={book.title}
author={book.author}
date={book.date}
desc={book.desc}
category={book.category}
length={book.length}
avgRating={book.avgRating}
ratings={book.ratings}
language={book.language}
isbn={book.isbn}
username={user.email}
deleteButton={true}
redirectAfterDelete={"/"}
>
<ReadingProgress
percentage={read}
isbn={book.isbn}
user={user.email}
/>
</BookContainer>
)}
{!fetchedBook && (
<Wrapper minHeight="50vh">
<Loading
minHeight="30vh"
src={LoadingIcon}
alt="Loading icon"
className="rotating"
/>
</Wrapper>
)}
<Header header="Notes" subheader="All your notes on this book">
<AddNoteButton
to="/add-note"
state={{
isbn: isbn,
user: user,
}}
>
<AddIcon color="#6b6b6b" />
Add Note
</AddNoteButton>
</Header>
{fetchedNotes && (
<NoteContainer>
{notes.map((note) => {
return (
<NoteBlock
title={note.noteTitle}
date={note.date}
key={note._noteID}
noteID={note._noteID}
bookID={isbn}
/>
);
})}
{notes.length === 0 && (
<NoNotesMessage>
You don't have any notes for this book yet.
</NoNotesMessage>
)}
</NoteContainer>
)}
</Layout>
);
};
The way you have written your fetch functionality in your custom hook useFetchMongoField you have no flag to indicate that a request was already issued and you are currently just waiting for the response. So whenever any property in your useEffect dependency array changes, your request will be issued a second time, or a third time, or more. As long as no response came back.
You can just set a bool flag when you start to send a request, and check that flag in your useEffect before sending a request.
It may be the case that user and isbn are not set initially, and when they are set they each will trigger a re-render, and will trigger a re-evalution of your hook and will trigger your useEffect.
I was able to fix this issue.
The problem was I was assuming the user object was remaining the same across renders, but some of its properties did in fact change. I was only interested in checking the email property of this object which doesn't change, so I only passed user?.email to the dependency array which solved the problem.
I want to save state to localStorage when a component is unmounted.
This used to work in componentWillUnmount.
I tried to do the same with the useEffect hook, but it seems state is not correct in the return function of useEffect.
Why is that? How can I save state without using a class?
Here is a dummy example. When you press close, the result is always 0.
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Example() {
const [tab, setTab] = useState(0);
return (
<div>
{tab === 0 && <Content onClose={() => setTab(1)} />}
{tab === 1 && <div>Why is count in console always 0 ?</div>}
</div>
);
}
function Content(props) {
const [count, setCount] = useState(0);
useEffect(() => {
// TODO: Load state from localStorage on mount
return () => {
console.log("count:", count);
};
}, []);
return (
<div>
<p>Day: {count}</p>
<button onClick={() => setCount(count - 1)}>-1</button>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => props.onClose()}>close</button>
</div>
);
}
ReactDOM.render(<Example />, document.querySelector("#app"));
CodeSandbox
I tried to do the same with the useEffect hook, but it seems state is not correct in the return function of useEffect.
The reason for this is due to closures. A closure is a function's reference to the variables in its scope. Your useEffect callback is only ran once when the component mounts and hence the return callback is referencing the initial count value of 0.
The answers given here are what I would recommend. I would recommend #Jed Richard's answer of passing [count] to useEffect, which has the effect of writing to localStorage only when count changes. This is better than the approach of not passing anything at all writing on every update. Unless you are changing count extremely frequently (every few ms), you wouldn't see a performance issue and it's fine to write to localStorage whenever count changes.
useEffect(() => { ... }, [count]);
If you insist on only writing to localStorage on unmount, there's an ugly hack/solution you can use - refs. Basically you would create a variable that is present throughout the whole lifecycle of the component which you can reference from anywhere within it. However, you would have to manually sync your state with that value and it's extremely troublesome. Refs don't give you the closure issue mentioned above because refs is an object with a current field and multiple calls to useRef will return you the same object. As long as you mutate the .current value, your useEffect can always (only) read the most updated value.
CodeSandbox link
const {useState, useEffect, useRef} = React;
function Example() {
const [tab, setTab] = useState(0);
return (
<div>
{tab === 0 && <Content onClose={() => setTab(1)} />}
{tab === 1 && <div>Count in console is not always 0</div>}
</div>
);
}
function Content(props) {
const value = useRef(0);
const [count, setCount] = useState(value.current);
useEffect(() => {
return () => {
console.log('count:', value.current);
};
}, []);
return (
<div>
<p>Day: {count}</p>
<button
onClick={() => {
value.current -= 1;
setCount(value.current);
}}
>
-1
</button>
<button
onClick={() => {
value.current += 1;
setCount(value.current);
}}
>
+1
</button>
<button onClick={() => props.onClose()}>close</button>
</div>
);
}
ReactDOM.render(<Example />, document.querySelector('#app'));
<script src="https://unpkg.com/react#16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
This will work - using React's useRef - but its not pretty:
function Content(props) {
const [count, setCount] = useState(0);
const countRef = useRef();
// set/update countRef just like a regular variable
countRef.current = count;
// this effect fires as per a true componentWillUnmount
useEffect(() => () => {
console.log("count:", countRef.current);
}, []);
}
Note the slightly more bearable (in my opinion!) 'function that returns a function' code construct for useEffect.
The issue is that useEffect copies the props and state at composition time and so never re-evaluates them - which doesn't help this use case but then its not what useEffects are really for.
Thanks to #Xitang for the direct assignment to .current for the ref, no need for a useEffect here. sweet!
Your useEffect callback function is showing the initial count, that is because your useEffect is run only once on the initial render and the callback is stored with the value of count that was present during the iniital render which is zero.
What you would instead do in your case is
useEffect(() => {
// TODO: Load state from localStorage on mount
return () => {
console.log("count:", count);
};
});
In the react docs, you would find a reason on why it is defined like this
When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier,
effects run for every render and not just once. This is why React also
cleans up effects from the previous render before running the effects
next time.
Read the react docs on Why Effects Run on Each Update
It does run on each render, to optimise it you can make it to run on count change. But this is the current proposed behavior of useEffect as also mentioned in the documentation and might change in the actual implementation.
useEffect(() => {
// TODO: Load state from localStorage on mount
return () => {
console.log("count:", count);
};
}, [count]);
The other answer is correct. And why not pass [count] to your useEffect, and so save to localStorage whenever count changes? There's no real performance penalty calling localStorage like that.
Instead of manually tracking your state changes like in the accepted answer you can use useEffect to update the ref.
function Content(props) {
const [count, setCount] = useState(0);
const currentCountRef = useRef(count);
// update the ref if the counter changes
useEffect(() => {
currentCountRef.current = count;
}, [count]);
// use the ref on unmount
useEffect(
() => () => {
console.log("count:", currentCountRef.current);
},
[]
);
return (
<div>
<p>Day: {count}</p>
<button onClick={() => setCount(count - 1)}>-1</button>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => props.onClose()}>close</button>
</div>
);
}
What's happening is first time useEffect runs, it creating a closure over the value of state you're passing; then if you want to get the actual rather the first one.. you've two options:
Having the useEffect with a dependency over count, which will refresh it on each change on that dependency.
Use function updater on setCount.
If you do something like:
useEffect(() => {
return () => {
setCount((current)=>{ console.log('count:', current); return current; });
};
}, []);
I am adding this solution just in case someone comes here looking for an issue trying to do an update based on old value into a useEffect without reload.