REACT JS – Axios API Fetching Example Code

How to fetch API data in React JS using Axios and store it in the state variable. In the example code below we are taking data from the API using axios and storing the data to a state variable.

import axios from "axios";


function App() {
  const [todos, setTodos] = useState([]);

  const dispatch = useDispatch()


  useEffect(() => {
    axios({
      method: "get",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      url: `http://localhost:1337/list`,
      withCredentials: false,
    }).then((results) => {
      console.log(results.data);
      setTodos(results.data);
    });

  }, []); // <-- Have to pass in [] here! 

}

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *