Last active
October 26, 2019 10:45
-
-
Save sag1v/1e4005613179041f1667ec3e5d05d53d to your computer and use it in GitHub Desktop.
Markdium-React state update on an unmounted component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function useIsMountedRef(){ | |
| const isMountedRef = useRef(null); | |
| useEffect(() => { | |
| isMountedRef.current = true; | |
| return () => isMountedRef.current = false; | |
| }); | |
| return isMountedRef; | |
| } | |
| function Pets() { | |
| const [pets, dispatch] = useReducer(petsReducer, initialState); | |
| const isMountedRef = useIsMountedRef(); | |
| const onChange = ({ target }) => { | |
| dispatch({ type: "PET_SELECTED", payload: target.value }); | |
| }; | |
| useEffect(() => { | |
| if (pets.selectedPet) { | |
| dispatch({ type: "FETCH_PET" }); | |
| getPet(pets.selectedPet).then(data => { | |
| if(isMountedRef.current){ | |
| dispatch({ type: "FETCH_PET_SUCCESS", payload: data }); | |
| } | |
| }); | |
| } else { | |
| dispatch({ type: "RESET" }); | |
| } | |
| }, [pets.selectedPet, isMountedRef]); | |
| return ( | |
| <div> | |
| <select value={pets.selectedPet} onChange={onChange}> | |
| <option value="">Select a pet</option> | |
| <option value="cats">Cats</option> | |
| <option value="dogs">Dogs</option> | |
| </select> | |
| {pets.loading && <div>Loading...</div>} | |
| {pets.petData && <Pet {...pets.petData} />} | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment