Ads Top

How to fetch data with stateless component in react?

How to get API value using axios in react?
Fetching data in the stateless component with react we need to use hooks as useEffect() and useState() hooks, and also using axios plugins. 
Note: If your data is coming as a object then you need to use map() method other wise your data will not show. if you are as a string then use direct as variable.
This is simple example:
import React, { useEffectuseState } from 'react'
import axios from 'axios'

export default () => {

    let [testVarsettestVaruseState('');

    useEffect( () => {
        axios.get('https://jsonplaceholder.typicode.com/todos/')
        //.then(response => settestVar(response.data))
        .then(response => console.log(response.data))
    }, [])

    return(
        <>
           {testVar}
        </>
    )
}

................................................

const [userDatasetUserDatauseState({});

    useEffect(() => {
        axios.get(apiBaseUrl + 'api/users')
            .then(response => {
                // how to set my value: response.data.data
                setUserData(response.data.data)
               // console.log(response.data.data)
            }, error => {
                console.log(error)
            })
    }, [])

.......................................................

import React, { useStateuseEffect } from 'react';

import axios from 'axios';
export default() => {
  const [datasetData] = useState({ hits: [] });
  useEffect( () => {
    .then(response => setData(response.data))
  });
  return (
    <ul>
      {data.hits.map(item => (
        <li key={item.objectID}>
          <a href={item.url}>{item.title}</a>
        </li>
      ))}
    </ul>
  );
}
I have used API only for the test purpose. You can use your own API.

No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.