Home > Blockchain >  Unable to view data in react native using Axios from an API
Unable to view data in react native using Axios from an API

Time:04-28

I'm using Axios to retrieve my data from my API in this Class component in TSX. It doesn't give any error, it just doesn't show my Images or not even the data in a console.log. I'm now using a class component with tsx because in my previous attempts to let a animated slider work I used: Class component in jsx, Class component in tsx, Function in JSX with hooks aswell in TSX. At every attempt there were different errors that I couldn't solve that's why I'm using this strategy now and I guess I'm close now to the sollution, it's just the Data that's not viewing.

Thanks in advance

class MyComponent extends Component {
  componentDidMount() {
    LogBox.ignoreLogs(['Animated: `useNativeDriver`'])
  }

  position
  rotate: number
  rotateAndTranslate
  likeOpacity
  dislikeOpacity
  nextCardOpacity
  nextCardScale
  PanResponder

  imagesData: Images[]

  mySpecialFunction() {
    console.log('Images data:', this.imagesData)
  }

  constructor(props) {
    super(props)

    LogBox.ignoreLogs(['Animated: `useNativeDriver`'])

    axios
      .get<Images[]>(
        'https://api.thecatapi.com/v1/images/search?breed_ids=beng&include_breeds=true',
      )
      .then((response: AxiosResponse) => {
        this.imagesData = response.data
      })

    this.position = new Animated.ValueXY()
    this.state = {
      currentIndex: 0,
    }
    this.rotate = this.position.x.interpolate({
      inputRange: [-SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2],
      outputRange: ['-30deg', '0deg', '10deg'],
      extrapolate: 'clamp',
    })
    this.rotateAndTranslate = {
      transform: [
        {
          rotate: this.rotate,
        },
        ...this.position.getTranslateTransform(),
      ],
    }
    this.likeOpacity = this.position.x.interpolate({
      inputRange: [-SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2],
      outputRange: [0, 0, 1],
      extrapolate: 'clamp',
    })
    this.dislikeOpacity = this.position.x.interpolate({
      inputRange: [-SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2],
      outputRange: [1, 0, 0],
      extrapolate: 'clamp',
    })
    this.nextCardOpacity = this.position.x.interpolate({
      inputRange: [-SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2],
      outputRange: [1, 0, 1],
      extrapolate: 'clamp',
    })
    this.nextCardScale = this.position.x.interpolate({
      inputRange: [-SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2],
      outputRange: [1, 0.8, 1],
      extrapolate: 'clamp',
    })
  }
  UNSAFE_componentWillMount() {
    this.PanResponder = PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onPanResponderMove: (evt, gestureState) => {
        this.position.setValue({ x: gestureState.dx, y: gestureState.dy })
      },
      onPanResponderRelease: (evt, gestureState) => {
        if (gestureState.dx > 120) {
          Animated.spring(this.position, {
            toValue: { x: SCREEN_WIDTH   100, y: gestureState.dy },
            useNativedriver: true,
          }).start(() => {
            this.setState({ currentIndex: this.state.currentIndex   1 }, () => {
              this.position.setValue({ x: 0, y: 0 })
            })
          })
        } else if (gestureState.dx < -120) {
          Animated.spring(this.position, {
            toValue: { x: -SCREEN_WIDTH - 100, y: gestureState.dy },
            useNativedriver: true,
          }).start(() => {
            this.setState({ currentIndex: this.state.currentIndex   1 }, () => {
              this.position.setValue({ x: 0, y: 0 })
            })
          })
        } else {
          Animated.spring(this.position, {
            toValue: { x: 0, y: 0 },
            friction: 4,
            useNativedriver: true,
          }).start()
        }
      },
    })
  }
  renderUsers = () => {
    if (this.imagesData) {
      return this.imagesData
        .map((item, i) => {
          if (i < this.state.currentIndex) {
            return null
          } else if (i == this.state.currentIndex) {
            return (
              <Animated.View
                {...this.PanResponder.panHandlers}
                key={item.id}
                style={[
                  this.rotateAndTranslate,
                  {
                    height: SCREEN_HEIGHT - 120,
                    width: SCREEN_WIDTH,
                    padding: 10,
                    position: 'absolute',
                  },
                ]}
              >
                <Animated.View
                  style={{
                    opacity: this.likeOpacity,
                    transform: [{ rotate: '-30deg' }],
                    position: 'absolute',
                    top: 50,
                    left: 40,
                    zIndex: 1000,
                  }}
                >
                  <Text
                    style={{
                      borderWidth: 1,
                      borderColor: 'green',
                      color: 'green',
                      fontSize: 32,
                      fontWeight: '800',
                      padding: 10,
                    }}
                  >
                    LIKE
                  </Text>
                </Animated.View>
                <Animated.View
                  style={{
                    opacity: this.dislikeOpacity,
                    transform: [{ rotate: '30deg' }],
                    position: 'absolute',
                    top: 50,
                    right: 40,
                    zIndex: 1000,
                  }}
                >
                  <Text
                    style={{
                      borderWidth: 1,
                      borderColor: 'red',
                      color: 'red',
                      fontSize: 32,
                      fontWeight: '800',
                      padding: 10,
                    }}
                  >
                    NOPE
                  </Text>
                </Animated.View>
                <Image
                  style={{ height: '86%', width: null, borderRadius: 10 }}
                  source={{ uri: `${item.url}` }}
                />
                <View
                  style={{
                    backgroundColor: '',
                    color: 'black',
                    fontSize: 20,
                    fontWeight: '800',
                    position: 'absolute',
                    bottom: 95,
                    right: 40,
                    zIndex: 1000,
                    width: '85%',
                    height: '20%',
                    borderRadiusTop: 20,
                  }}
                >
                  <Text
                    style={{ color: 'white', fontSize: 32, fontWeight: '800' }}
                  >
                    Black cat
                  </Text>
                  <Text
                    style={{ color: 'white', fontSize: 18, fontWeight: '600' }}
                  >
                    Black cat family
                  </Text>
                  <View style={styles.iconen}>
                    <Ionicons style={styles.icon} name="timer" />
                    <Text style={styles.subtitle}>
                      {item.breeds[0].life_span}
                    </Text>
                    <Ionicons style={styles.icon} name="barbell-outline" />
                    <Text style={styles.subtitle}>
                      {item.breeds[0].weight.metric}
                    </Text>
                    <Ionicons style={styles.icon} name="earth" />
                    <Text style={styles.subtitle}>
                      {item.breeds[0].country_code}
                    </Text>
                  </View>
                </View>
              </Animated.View>
            )
          } else {
            return (
              <Animated.View
                key={item.id}
                style={[
                  {
                    opacity: this.nextCardOpacity,
                    transform: [{ scale: this.nextCardScale }],
                    height: SCREEN_HEIGHT - 120,
                    width: SCREEN_WIDTH,
                    padding: 10,
                    position: 'absolute',
                  },
                ]}
              >
                <Animated.View
                  style={{
                    opacity: 0,
                    transform: [{ rotate: '-30deg' }],
                    position: 'absolute',
                    top: 50,
                    left: 40,
                    zIndex: 1000,
                  }}
                >
                  <Text
                    style={{
                      borderWidth: 1,
                      borderColor: 'green',
                      color: 'green',
                      fontSize: 32,
                      fontWeight: '800',
                      padding: 10,
                    }}
                  >
                    LIKE
                  </Text>
                </Animated.View>
                <Animated.View
                  style={{
                    opacity: 0,
                    transform: [{ rotate: '30deg' }],
                    position: 'absolute',
                    top: 50,
                    right: 40,
                    zIndex: 1000,
                  }}
                >
                  <Text
                    style={{
                      borderWidth: 1,
                      borderColor: 'red',
                      color: 'red',
                      fontSize: 32,
                      fontWeight: '800',
                      padding: 10,
                    }}
                  >
                    NOPE
                  </Text>
                </Animated.View>
                <Image
                  style={{ height: '86%', width: null, borderRadius: 10 }}
                  source={{ uri: `${item.url}` }}
                />
              </Animated.View>
            )
          }
        })
        .reverse()
    }
  }
  render() {
    return (
      <View>
        <View>{this.renderUsers()}</View>
        <View style={{ height: SCREEN_HEIGHT - 80 }}>
          <ButtonVote />
        </View>
      </View>
    )
  }
}

CodePudding user response:

Try this way by using state for reflecting changes after API respond

class MyComponent extends Component {
  state = {
    imagesData: [],
  };

  // rest of the code remains the same

  componentDidMount() {
    axios.get(`xxxxxx`).then((res) => {
      const imagesData = res.data;
      this.setState({ imagesData });
    });
  }

  renderUsers = () => {
    if (this.state.imagesData) {
      return this.state.imagesData.map((item, i) => {}).reverse();
    }
  };
  render() {
    return <View></View>;
  }
}
  • Related