I
I
Ilya Korotkov2021-08-24 12:13:50
JavaScript
Ilya Korotkov, 2021-08-24 12:13:50

Preventing useEffect and its nested function from working?

Good day, dear forum users! I ask for your help in organizing the work of the useEffect hook.
Available:

const [sortedAuthors, setSortedAuthors] = React.useState([]);

React.useEffect(() => {
    if (sortedAuthors !== []) {
      sortingAuthorsByFirstSymbol();
    }
  }, [sortedAuthors]);

function sortingAuthorsByFirstSymbol() {
    if (sortedAuthors) {
        let initialSymbol = sortedAuthors[0][0];
        ...
}


1. The state, when changed, the hook should work. The state changes through the processing of other states, which in turn is launched by clicking on the button.
2. The hook itself, inside of which I placed the if condition so that it does not call the nested function when the state is still empty - i.e. on page load
3. A function in which I also placed an if condition so that it does not work when the state is empty.

Problem: both the hook and the function wanted to sneeze on conditional logic. For some reason, the interpreter reaches initialSymbol, then an error with undefined.
I would appreciate any advice on solving the problem. Architectural remarks will also come in handy - is the organization of the code itself correct.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-08-24
@brother_ilya

1) if (sortedAuthors !== []) is always true, because it is compared by reference with a newly created object
2) if sortingAuthorsByFirstSymbol changes sortedAuthors, then most likely the scheme of work here is wrong, it is better to do it through
useMemo And How.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question