'How can we pass a value to a context so it can return the proper data?

I created a application to explain and understand this better, here it is.

I've created a context to get data from "swapi.dev". At the end of the link we are passing a parameter page=1.

In the App we have a input that is getting a number.

How can we pass the input value to the context so it would return the proper data corresponding to the input?

Example: if we digit 3 in the input, the api returns the equivalent to page=3

There are just two files in the project. Here is a copy of my context api file:

import { createContext, useContext, useEffect, useState } from "react";
const axios = require("axios");

const ApiContext = createContext({});

export default function ApiProvider({ children }) {
  const [api, setApi] = useState([]);
  const ApiAddress = axios.create({
    baseURL: "https://swapi.dev/api/people"
  });

  useEffect(() => {
    ApiAddress.get("?page=1")
      .then((response) => setApi(response.data.results))
      .catch((err) => console.log(err));
  }, []);

  return (
    <ApiContext.Provider value={{ api, setApi }}>
      {children}
    </ApiContext.Provider>
  );
}

export const useApi = () => {
  const context = useContext(ApiContext);
  const { api, setApi } = context;
  return { api, setApi };
};

And my App file:

import { useState } from "react";
import { useApi } from "./context/api";

export default function App() {
  //data from api
  const { api, setApi } = useApi();

  //inputvalue
  const [inputValue, setInputValue] = useState(1);

  return (
    <>
      <h1>App</h1>
      <h2>Select Page</h2>
      <input
        type="number"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h3>Page: {inputValue}</h3>
      <table>
        <tbody>
          {api.map((apiElement, index) => (
            <tr>
              <th>{apiElement.name}</th>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source