10

I am trying to fetch server side data in JSON format in a table with Axios, but can't understand how to get every field like id, companyInfo etc.

json :

[
  {
    "id": 1,
    "companyInfo": 1,
    "receiptNum": 1,
    "receiptSeries": "АА",
    "customerName": "Mark",
    "customerSurname": "Smith",
    "customerMiddleName": "Jk",
    "customerPhone": "0845121",
    "services": [
      2,
      16
    ]
  }
]

axios :

 store.dispatch((dispatch) => {
dispatch({type: Actions.FETCH_DATA_START})
axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response })
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })

reducer :

export const initialState = {
  paymentReceipts: []
};

export default handleActions<FetchData>({
  [Actions.FETCH_DATA_START]: (state, action) => {
    return ;
  },
  [Actions.FETCH_DATA_ERROR]: (state, action) => {
    return;
  },
  [Actions.RECEIVE_DATA]: (state, action) => {
      console.log("DONE WITH STATE");
    return {...state, 
        paymentReceipts :  action.payload
    }
  }
}, initialState)

App

@connect(mapStateToProps, mapDispatchToProps)
export class App extends React.Component<App.Props, App.State> {

  constructor() {
    super();
  }

  render() {
    console.log("CONTAINER IS ");
    console.log(this.props.receiveData);

    return (
      <div className={style.normal}>

      </div>
    );
  }
}

function mapStateToProps(state: RootState) {
  return {
    receiveData: state.receiveData
  };
}

function mapDispatchToProps(dispatch) {
  return {

  };
}

This is what I get from console.log:

This is what I get from <code>console.log</code>

So how to get this values from JSON?

5 Answers 5

14

You will get all your data into response.data.

axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response.data }) //Change
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, its fixed situation, but i still dont know how to get pair elements like id = 1, receiptSeries = АА etc
just try to print console.log(response.data)
6

To access a single attribute within your json-response you can simply do:

response.data.<attribute>

e.g.:

   axios.get("http://localhost:3004/paymentReceipts")
  .then((response) => {
    dispatch({ type: Actions.RECEIVE_DATA, payload: response.data, id: response.data.id }) //Change
  }).catch((err) => {
    dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
  })

Depending on the structure of your json and how it's formatted (e.g. array of objects) you have to iterate through it.

2 Comments

Is data a keyword from axios library?
According to the docs there are several keywords you can call on response. For example: response.data, response.status, response.headers etc. I'm not confident enough to say that this works in every enviroment and setup, but yes, it is a "keyword" for an axios response
2

If you've received text instead of JSON,just like I did,

With async/await, it's simply,

let results = await axios.get("http://localhost:3004/paymentReceipts")
try {
  let response = JSON.parse(results.request.response)  
  dispatch({ type: Actions.RECEIVE_DATA, payload: response })
} catch(err) {
  dispatch({type: Actions.FETCH_DATA_ERROR, payload: err})
}

Comments

0
import  Axios  from "axios";
import React ,{useState}from "react";
import { useNavigate} from 'react-router-dom';

const FrtchData = () =>
{
    const navigate = useNavigate();
const [emp,setEmp]=useState([])
Axios.get("https://fakestoreapi.com/products")
.then(res=>setEmp(res.data))

return (
    <div>

    {
        emp.map((emp,index) => <li key={index}>{emp.title}</li>)
    }
     <button onClick={()=>navigate("/home")}>Logout</button>
     
    </div>
)

}
export default FrtchData

2 Comments

What does this code do? What is impoved? Can you edit the post so that future comers know what this code means?
You should add explanation.
0
import  Axios  from "axios";
import React ,{useState,useEffect}from "react";
import {useNavigate} from 'react-router-dom';

const FrtchData = () =>
{
    const navigate = useNavigate();
   
         const [users,setUsers] =useState([])
        useEffect (() =>{
            const asynfunc=async () =>{
                await Axios.get('https://fakestoreapi.com/products')
                .then(res=>setUsers(res.data))
            }
            asynfunc()
        },[])
        
        return (<div>
            {
                users.map((users,index) => <li key={index}>{users.title} </li>)
            }
            <button onClick={()=>navigate("/home")}>Logout</button>
        </div>)

}
export default FrtchData

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.