darkflame
darkflame

Reputation: 383

How to return variables to html from axios api on React

I would like to return a single variable on my website that is founded in my API REST. I'm using Axios to integrate my backend to my frontend.

import api from '../../api';

async function handleBooks(e){
    e.preventDefault();
    
    const data = {
        title,
        reservation,
        rent,
        devolution
    }; 

    try{
        const response = await api.get('books', data);
        console.log(response); //it is working!
    }catch(err){
        console.log('!response');
    }
}

 return(
    //I would like to return one of those variables upside mentioned, for example: 'title'.
    <div>{response.data.title}<div/>
 );

Upvotes: 0

Views: 58

Answers (2)

darkflame
darkflame

Reputation: 383

Answer:

+ const [datas, setData] = useState([]);
 + try{
            const response = await api.get('books', data);
            setData(response.data);
            console.log(response.data);
        }
    <ul>
        {datas.map(data => (
            <li key={data.id}>
            <p>{data.title}</p>
            <p>{data.rent}</p>
            <p>{data.devolution}</p>
            <p>{data.reservation}</p>
            </li>
         ))}
</ul>

Upvotes: 0

Michał Lach
Michał Lach

Reputation: 1278

Set response as React state:

import api from '../../api';
import React, {useState} from 'react

async function handleBooks(e){
    e.preventDefault();
    const [data, setData] = useState([])
    
    const data = {
        title,
        reservation,
        rent,
        devolution
    }; 

    try{
        const response = await api.get('books', data);
        setData(response.data)
        console.log(response); //it is working!
    }catch(err){
        console.log('!response');
    }
}

 return(
    //I would like to return one of those variables upside mentioned, for example: 'title'.
    <div>{data && data.title}<div/>
 );

Upvotes: 1

Related Questions