简体   繁体   中英

How do i loop through certain number of IDs when calling a REST API url in state property?

I am building an application using "Rick and Morty" REST API, In the documentation, it is stated that we can request any number of characters out of 493 characters using certain query string.

For example, the below URL can request character with the ids 34 and 56,but if we want to request more characters at a single time we have to provide all the id in the array, and there are total 493 characters

https://rickandmortyapi.com/api/character/[34,56]

I have a CardList component which loops over card component and shows up the properties.

import React from "react";
import axios from "axios";
import Card from "./Card";

class CardList extends React.Component {
  state = {
    url: `https://rickandmortyapi.com/api/character/${[...Array(493).keys()]}`,
    character: []
  };

  async componentDidMount() {
    const res = await axios.get(this.state.url);

    this.setState({
      character: res.data
    });
  }

  render() {
    return (
      <div>
        {this.state.character.map(character => (
          <Card
            key={character.id}
            id={character.id}
            name={character.name}
            status={character.status}
            species={character.species}
            gender={character.gender}
            type={character.type ? character.type : "Unknown"}
          />
        ))}
      </div>
    );
  }
}

export default CardList;

What i want to do:

I want to write a function in the "state" which fill up the array from 1 to 493, but where do i write the function?

What i tried to do:

I tried to use template strings in the state and wrote a function to create a range for the array like below

url: ` https://rickandmortyapi.com/api/character/ ${function loop(){var x = 0; while(x<493){ x++; return x}}}

something like above, but i'm not sure if i can write a function like above in the template strings.

Help me out, please.

Your example seems to do what you want, you're just missing the wrapping square brackets. Change to this:

const url = `https://rickandmortyapi.com/api/character/[${[...Array(493).keys()]}]`;

By the way, there doesn't appear to be any reason to keep this in the state. Would recommend moving this to a constant outside of the state.

Basically your code is ok. You just don't need to keep anything in the state. In case you need to compute a different set of IDs I suggest you run the code in componentDidMount() right before your HTTP request via Axio or inside a method or a pure function:

  ...

  getUrl(count) {
    // Array indexes start from 0 we wanna map them and add 1
    // and at the end we join them with a comma `,`
    const ids = Array(count).fill(null).map((_, idx) => idx +1).join(','); // '1,2,3...,300'
    return `https://rickandmortyapi.com/api/character/[${ids}]`;
  }
  async componentDidMount() {
    const res = await axios.get(this.getUrl(300));

    this.setState({
      character: res.data
    });
  }

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