Home > Enterprise >  React-Native) How to retrieve object values ​in an array | Minified React error #301
React-Native) How to retrieve object values ​in an array | Minified React error #301

Time:10-26

export default function App() {
  const [arrays, setArrays] = useState([]);
  const initArray = [
    { id: 2023, solveTF: false, rightTF: false },
    { id: 2025, solveTF: false, rightTF: false },
  ];
  setArrays(initArray);
  
  const idArrays = [2022,2023,2025,2027];
  const idSearch = () => {
    for (let i = 0; i < idArrays.length; i  ) {
      let idArray = idArrays[i]
      let newArray = arrays.filter((item) => item.id == idArray).map();
      console.log(newArray);
    }};

  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={() => idSearch()}>
        <Card>
          <AssetExample />
        </Card>
      </TouchableOpacity>
    </View>
  );
}

I want to check if a value in idArrays exists in arrays. If not, I want to add a new object to the arrays. What did I do wrong and what should I do?

I worked with snack.expo.dev. [Minified React error #301] is occurred.

CodePudding user response:

Initialize the state inside the useState to avoid an unwanted rerender.

For what you want is better to use some inside of filter to check the ids that aren't in arrays and then use setArrays to add a new object for each id not already in.

export default function App() {
    // Initialize inside useState
    const [arrays, setArrays] = useState([
        { id: 2023, solveTF: false, rightTF: false },
        { id: 2025, solveTF: false, rightTF: false },
    ]);

    const idArrays = [2022, 2023, 2025, 2027];
    const idSearch = () => {
        const notExistInArrays = idArrays.filter(id => !arrays.some(item => item.id === id));
        setArrays(prevArrays => [
            ...prevArrays,
            ...notExistInArrays.map(id => ({ id, solveTF: false, rightTF: false }))
        ]);
    };

    return (
        <View style={styles.container}>
            <TouchableOpacity onPress={() => idSearch()}>
                <Card>
                    <AssetExample />
                </Card>
            </TouchableOpacity>
        </View>
    );
}
  • Related