0

I have some recoil state, that i want to reset.

import { useRecoilValue, useResetRecoilState, useSetRecoilState } from 'recoil';
...
  //should be used for flushing the global recoil state, whenever a user submits an invoice
  const resetLabelInvoiceState = useResetRecoilState(labelInvoiceState);
  const resetMetaDataState = useResetRecoilState(metadataState);
  const resetGlobalAnnotationsState = useResetRecoilState(globalAnnotationState)

I have made function, that i suppoes to reset all the states like this. I have both tried with and without the reset function.

const flushRecoilState = () =>{
     console.log('flushed state')
     return(
    resetLabelInvoiceState(),
    resetMetaDataState(),
    resetGlobalAnnotationsState()
     )
   }
...
        flushRecoilState()
        return history.push('/historyinvoices')
...

When i check the state it is not reset. Is it because the `useResetRecoilState´ is not working properly from the library, is not implemented properly, or is there some other problem.

I could just use the regular useRecoilState hook, and just set the state back to the default value.

Does anybody know why this could be?

Kristoffer Tølbøll
  • 3,157
  • 5
  • 34
  • 69
  • 1
    Could you share a minimal CodeSandbox to play with, please? – NoriSte Aug 13 '20 at 06:24
  • 1
    Why are you doing `return(resetLabelInvoiceState(), resetMetaDataState(), resetGlobalAnnotationsState())`? It does not make sense, all the functions are called but just the result of the first one is returned. More: the `useResetRecoilState` returns nothing if I remember correctly – NoriSte Aug 13 '20 at 06:26
  • 1
    When do you check the reset value? This is a async operation. Calling the reset function returned by the hook does not immediately propagate the change to every single subscribed component. It works just like set state in vanilla React. – Johannes Klauß Aug 29 '20 at 08:55

1 Answers1

0

I had the same problem today, it turns out to be my own fault. Just put it here for future reference.

My problem was that I changed the set method in the selector, if you customized the set method, you need to check if the incoming value is a DefaultValue.

const targetYear = selector({
  key: 'targetYear',
  get: ({get}) => get(targetYearAtom),
  set: ({set, get}, method) => {
    const currentTargetYear = get(targetYearAtom);
    switch(method) {
      case 'prevYear':
        set(targetYearAtom, currentTargetYear - 1);
        return;
      case 'nextYear':
        set(targetYearAtom, currentTargetYear + 1);
        return;
      default:
        if (method instanceof DefaultValue) {
          set(targetYearAtom, method);
        }
        return;
    }
  },
})
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Yao
  • 88
  • 1
  • 4