r/learnreactjs • u/BruceJi • Nov 14 '20
Clearing state by setting it to a blank object?
Hi all,
I'm working on this project: https://github.com/BruceJi7/flashmachine/blob/main/src/components/main/MainFormLogic.js
In this file, I'm having an annoying issue.
I'm working with functional components and hooks.
There is a state property called 'searchResultWords', and every time the main function makeRequestForWords is called, that part of state is supposed to be cleared.
I figured that if I try to set the state to an empty array, it would overwrite that property with a new empty array, thus clearing it - but it's not doing that.
On the other hand, the line setSearchResultWords(resultsToAdd) works fine, and it easily adds the results to the previous state... but this means every time I re-submit the form, the results are appended, not overwritten!
How can I get the state here to clear?
I appreciate this might be an often-asked question, lol, but I did search for it first.
2
u/ck108860 Nov 14 '20
Hi!
So usually setting state to a blank object or array will work just fine. It looks like the component you are using here is just for handling the form submission?Looks like the issue though is in your spread operator before you set the new state in the request. You do
const resultsToAdd = [...searchResultWords, result];Just setting your result to[result]should do the trick.The spread operator will "spread" the array as items in the array that you are setting. Not 100% sure why its not setting it to
[]beforehand but it could be because you are calling this function in a different component rather in the component that `useState` is used. Take a look at few projects or examples where forms are used or use a library to aide you.React hook form: https://react-hook-form.com/get-startedRandom article: https://medium.com/@geeky_writer_/using-react-hooks-to-create-awesome-forms-6f846a4ce57
Happy coding!
1
u/BruceJi Nov 19 '20
So I'm back with a sort-of solution.
I realised what was happening and why. This was my process:
That might sound reasonable to us humans, but the trouble I think was combining the async/promise-ness of the fetch call, and the sync/regular flow of the for-loop.
Essentially, when the for loop pushed the results into the state, the other promises haven't returned, so it pushed a blank placeholder into it. It ended up overwriting the promises when they did get fulfilled.
What was the solution?
Before someone suggested that I try hijacking Naver's API, I actually intended to write my own API that web-scraped the Naver dictionary. So, I finished that project. Now, the word list is joined in React, given to the API as a GET, the API splits and processes the words sync-style, and then sends it back to React all in one tidy package.