0

I have a problem to put the result of an API request into an array value in my react native app.

this is the called function

    export function getNewFilmFromApi(page) {
    return fetch(
    'https://api.themoviedb.org/3/discover/movie?api_key=' +
      API_TOKEN +
      '&release_date.gte=2019-10-01&release_date.lte=2019-12-31&language=fr&page=' +
      page,
  )
    .then(response => response.json())
    .catch(error => console.error(error));
}

and this is how I'm trying to put the returned value into the array :

    const projects = [
  {
    title: getNewFilmFromApi().then(data => {
      return data.results[0].title;
    }),
    image: require('../Images/background.jpg'),
    author: 'Liu Yi',
    text: 'kkkk',
  },
  {
    title: 'The DM App - Ananoumous Chat',
    image: require('../Images/background.jpg'),
    author: 'Chad Goodman',
    text: 'kjhgfhjkl',
  },
  {
    title: 'Nikhiljay',
    image: require('../Images/background.jpg'),
    author: "Nikhil D'Souza",
    text: 'jjjjjj',
  },
];

I can see with console.log that there's a value for data.results[0].title but I can't put it in the array!

This is the error I have when I try to do this :

enter image description here

this is my render function and everything work except the title which I want to return it from API.

    render() {
    return (
      <Container>
        <AnimatedMask style={{opacity: this.state.opacity}} />
        <Animated.View
          style={{
            transform: [
              {translateX: this.state.pan.x},
              {translateY: this.state.pan.y},
            ],
          }}
          {...this._panResponder.panHandlers}>
          <Project
            title={projects[this.state.index].title}
            image={projects[this.state.index].image}
            author={projects[this.state.index].author}
            text={projects[this.state.index].text}
            canOpen={true}
          />
        </Animated.View>
        <Animated.View
          style={{
            position: 'absolute',
            top: 230,
            left: 0,
            zIndex: -1,
            width: '100%',
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            transform: [
              {scale: this.state.scale},
              {translateY: this.state.translateY},
            ],
          }}>
          <Project
            title={projects[getNextIndex(this.state.index)].title}
            image={projects[getNextIndex(this.state.index)].image}
            author={projects[getNextIndex(this.state.index)].author}
            text={projects[getNextIndex(this.state.index)].text}
          />
        </Animated.View>
        <Animated.View
          style={{
            position: 'absolute',
            top: 240,
            left: 0,
            zIndex: -2,
            width: '100%',
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            transform: [
              {scale: this.state.thirdScale},
              {translateY: this.state.thridTranslateY},
            ],
          }}>
          <Project
            title={projects[getNextIndex(this.state.index + 1)].title}
            image={projects[getNextIndex(this.state.index + 1)].image}
            author={projects[getNextIndex(this.state.index + 1)].author}
            text={projects[getNextIndex(this.state.index + 1)].text}
          />
        </Animated.View>
      </Container>
    );
  }
}

export default connect(mapStateToProps)(Card);

const Mask = styled.View`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.25);
  z-index: -3;
`;

const AnimatedMask = Animated.createAnimatedComponent(Mask);

const Container = styled.View`
  flex: 1;
  justify-content: center;
  align-items: center;
  background: #f0f3f5;
  margin-top: 80;
`;

const Text = styled.Text``;
var test;

const projects = [
  {
    title: getNewFilmFromApi().then(data => {
      return data.results[0].title;
    }),
    image: require('../Images/background.jpg'),
    author: 'Liu Yi',
    text: 'kkkk',
  },
  {
    title: 'The DM App - Ananoumous Chat',
    image: require('../Images/background.jpg'),
    author: 'Chad Goodman',
    text: 'kjhgfhjkl',
  },
  {
    title: 'Nikhiljay',
    image: require('../Images/background.jpg'),
    author: "Nikhil D'Souza",
    text: 'jjjjjj',
  },
];

Can you give any solution to display the value into the array please ?

thank you !

1 Answer 1

1

The way you're trying to populate your array with results from an API call will not work.

Your API call is asynchronous and it returns a Promise. Therefore you have to wait for your API call to finish and for the Promise to resolve, then update your projects array when your component renders.

I suggest you store your projects array in a state and make an API call when your component renders for the first time, like in the following simplified example:

function getNewFilmFromApi(page) {
  return fetch(`https://jsonplaceholder.typicode.com/todos/1`).then(res =>
    res.json()
  );
}

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      fetchError: false,
      isLoading: true,
      projects: [
        { title: null, author: `Liu Yi` },
        { title: `The DM App - Anonymous Chat`, author: `Chad Goodman` },
        { title: `Nikhiljay`, author: `Nikhil D'Souza` }
      ]
    };
  }

  componentDidMount() {
    const handleResponse = data => {
      const { title } = data;

      // assuming you just want to update
      // the first item in the `projects` array
      const nextProjects = [...this.state.projects];
      nextProjects[0].title = title;

      this.setState({
        projects: nextProjects,
        isLoading: false
      });
    };
    const handleError = err => {
      this.setState({
        apiError: true,
        isLoading: false
      });
    };

    getNewFilmFromApi()
      .then(handleResponse)
      .catch(handleError);
  }

  render() {
    const { apiError, isLoading, projects } = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }
    if (!isLoading && apiError) {
      return <p>Error loading projects</p>;
    }
    return <p>{JSON.stringify(projects)}</p>;
  }
}

Here's a link to a working example:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. It works and it is well explained. ty.
@amin89 glad I was able to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.