Home > Software design >  Display informations React Native
Display informations React Native

Time:11-23

I'm trying to display the retrieved information in my back-end. The recovery goes well only, when I use "array.push" in order to put this information in my array it does not work. I also tried to use a useState but for some reason my program runs in an infinite loop.

import React, {useState} from "react";
import {View, Text, Image} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
const jwtDecode = require("jwt-decode");
import {useDispatch} from "react-redux";

import * as authAction from "../redux/actions/authAction";

const FavoriteScreen = (props) => {
  const [id, setId] = useState("");
  const [informations, setInformations] = useState([]);
  const dispatch = useDispatch();

  let array = [];
  const checkToken = async () => {
    const token = await AsyncStorage.getItem("token");
    if (!token) {
      console.log("coucou le token n'existe pas");
      Alert.alert("Vous n'êtes pas connecté à un compte existant");
      return;
    }
    const decoded = jwtDecode(token);
    setId(decoded._id);
  };
  checkToken();
  dispatch(authAction.Favorite(id))
    .then((response) =>
      response.array.map((data) => {
        array.push(data);
        setInformations(array);
      })
    )
    .catch((error) => {
      console.error(error);
    });

  return (
    <View>
      {informations.map((data) => {
        <Text>{data["image_url"]}</Text>;
      })}
    </View>
  );
};

export default FavoriteScreen;

CodePudding user response:

Currently, you're having an infinite loop because your API call is being called on the "rendered side" of the component. You have two choices, either use a Class Component to organize your API call, or continue using the Functional Component approach and use the useEffect hook

Also another problem is that your API call will not wait for the id to be filled, so we need to wait to have the token id before making the API call

Class Component

import React, { useState } from "react";
import { View, Text, Image } from "react-native";
import { useDispatch } from "react-redux";
import AsyncStorage from "@react-native-async-storage/async-storage";

const jwtDecode = require("jwt-decode");

const FavoriteScreen = (props) => {
  const [informations, setInformations] = useState([]);
  const dispatch = useDispatch();

  const getToken = async () => {
    const token = await AsyncStorage.getItem("token");
    if (!token) {
      console.log("coucou le token n'existe pas");
      Alert.alert("Vous n'êtes pas connecté à un compte existant");
      return "";
    }

    const decoded = jwtDecode(token);
    return decoded._id;
  };

  useEffect(async () => {
    const id = await getToken();

    if (!id) return;

    dispatch(authAction.Favorite(id))
      .then((response) => {
        const newArray = response.array;

        setInformations(newArray);
      })
      .catch((error) => {
        console.error(error);
      });

  }, []);

  return (
    <View>
      {informations.map((data, index) => (
        <Text key={`information_${index}`}>{data["image_url"]}</Text>
      ))}
    </View>
  );
}

export default FavoriteScreen;

Note: this way it will work as the equivalent of componentDidMount from the component lifecycle

  • Related