Home > other >  connect counter with items in an array react hooks
connect counter with items in an array react hooks

Time:02-17

I have a counter where I can decrement and increment the counter. I have also an array with items like so:

  const gitHubRepos = [
    'repo0',
    'repo1',
    'repo2',
    'repo3',
  ]

I need to use the counter as an index for the above array (repo0 if the counter is 0, repo1 if it's 1, ...) and fetch information about the GitHub repository from GitHub's API: https://api.github.com/repos/{repoName}. But how can I connect both the counter with the array and at the same time fetch information for a specific repo?

CodePudding user response:

You can use useEffect to fetch depending on your counter. e.g.:

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [counter, setCounter] = useState(0)
  const gitHubRepos = [
    'repo0',
    'repo1',
    'repo2',
    'repo3',
  ]
  useEffect(()=>{
    console.log(`${gitHubRepos[counter]}`)
    fetch(`https://api.github.com/repos/${gitHubRepos[counter]}`);

  },[counter])
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={()=>setCounter(counter 1)}>increment</button>
    </div>
  );
}
  • Related