简体   繁体   中英

Can't update state array using hooks on findIndex condition

I have a bunch of data as such

const myArr = [
    { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "squat", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "shoulder", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "deadlift", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "deadlift", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "squat", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "shoulder", sets: 2 }] },
    { test1: "", test2: "b", exercises: [{ exercise: "shoulder", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "shoulder", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "squat", sets: 2 }] },
    { test1: "", test2: "a", exercises: [{ exercise: "situps", sets: 2 }] },
];

I am trying to store each 'exercise' that is listed, I don't need a tally of them just if it occurs once, stick it into the state array and ignore it if it comes up again so as not to add it again. ie as an example

const results = ['Deadlift', 'Bench', 'Squats', 'Shoulder']

Outside of react, I could just use something as such and I'd store each value the one time:

const storage = [];

for (let item of myArr) {
    for (let i of item.exercises) {
        if (storage.findIndex((v) => v === i.exercise) === -1) {
            storage.push(i.exercise);
        }
    }
}
console.log(storage);

However I can't get this to work within useEffect and useState hooks. Say I have the same data, If I do the same script inside useEffect it pays no attention to whether the string is already inside the state hook array, and will just seemingly add it anyway, regardless of my findIndex condition. So I end up with each exercise repeating however many times it occurs within the data as opposed to just the single reference to it.

useEffect(() => {
        if (allEntries.loaded) {
            for (let item of allEntries.entries) {
                for (let i of item.exercises) {
                    if (myState.findIndex((v) => v === i.exercise) === -1) {
                        setMyState((prev) => [...prev, i.exercise]);
                    }
                }
            }
        }
    }, [allEntries]);

Can someone explain where I've gone wrong?

flatMap and Set :

const myArr = [ <your data> ]
const uniqueExercises = [
  ...new Set(myArr.flatMap(x => x.exercises).map(x => x.exercise))
]

directly with setState :

setState([
  ...new Set(entries.flatMap(x => x.exercises).map(x => x.exercise))
])

 const myArr = [ { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "squat", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "shoulder", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "deadlift", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "deadlift", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "squat", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "shoulder", sets: 2 }] }, { test1: "", test2: "b", exercises: [{ exercise: "shoulder", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "shoulder", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "bench", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "squat", sets: 2 }] }, { test1: "", test2: "a", exercises: [{ exercise: "situps", sets: 2 }] }, ]; console.log([...new Set(myArr.flatMap(x => x.exercises).map(x => x.exercise))])

Although this has already been answered, I thought I might as well put this here anyway.

You can create a temporary new state and modify that directly without having to worry about the async nature of setState updates.

For Example:

useEffect(() => {
    if (allEntries.loaded) {
        setMyState(currentState => {
            const newState = [...currentState];

            for (let item of allEntries.entries) {
                for (let i of item.exercises) {
                    if (newState.findIndex((v) => v === i.exercise) === -1) {
                        newState.push(i.exercise);
                    }
                }
            }

            return newState;
        });
    }
}, [allEntries]);

To avoid having to use myState inside of the useEffect , which some linters will complain about if you don't add it to the dependency array, you can move more of the useEffect code inside of the setMyState callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM