I am unable to extract data from json - React-js

Asked

Viewed 194 times

2

gentlemen(as).

I am unable to extract a data to send to api. in the /cases path the api provides json data.

useEffect(()=>  {
    api.get('cases',{

    }).then(response =>{
        setcases(response.data)
    })
}, [])

When accessing the route cases, and render it is like this: inserir a descrição da imagem aqui

each case has an id that comes from the database (in the image would be 23 and 24) and I need to send this ID to the back when I sign up for it.

Here in {case.id} I bring the case id of the mysql table but I am not able to send to api this same given in the post method, and here comes the problem, how can I do it? what are the ways to capture this ID value? I’m using Axios.

async function handleInsc(){

    try {

        const config ={
            headers:{Authorization:userid}
        }

         await api.post('cases/inscMyCases',{
            cases_ids:cases.id/  */aqui vai o id*/
         },config)

        alert('Inscrito')

    } catch (error) {
        alert('erro na inscrição')

    }

}

below the full code.

import React,{useEffect, useState} from 'react'
import {Link, useHistory} from 'react-router-dom'
import {FiTrash2,FiPhoneForwarded,FiPower} from 'react-icons/fi'

import  './styleCases.css'

import api from '../../services/api'

export default function Profile(){
    const[cases, setcases] = useState([])   
    const history =useHistory()

    const usuario = localStorage.getItem('userName')
    const userid = localStorage.getItem('userId')
    useEffect(()=>  {
        api.get('cases',{

        }).then(response =>{
            setcases(response.data)

        })
    },[])


    function handleLogout(){
        localStorage.clear()
        history.push('/')
    }

    async function handleInsc(){

        try {

            const config ={
                headers:{Authorization:userid}
            }

             await api.post('cases/inscMyCases',{
                cases_ids:caso.id/*/aqui tem soluçao*/
             },config)

            alert('Inscrito')

        } catch (error) {
            alert('erro na inscrição')

        }

    }

    return(
        <div className="profile-container">
            <header>
                <span>SEJA BEM VINDO(a) {usuario}</span>

                <Link className="button" to="/alerts/newCase">Cadastrar um alerta de trabalho</Link>
                <Link className="button" to="profile">Volte para sua pagina de perfil</Link>


                <button onClick={handleLogout} type="button"></button>
                <FiPower size={18} color="#e02041"></FiPower>

            </header>

            <h1>Casos Cadastrados</h1>

                <ul>{cases.map(caso =>( 
                    <li key={cases.id}>
                    <strong>CASO:{caso.id}</strong>
                    <p>{caso.title}</p>


                    <strong>DESCRIÇÃO:</strong>
                    <p>{caso.description}</p>

                    <strong>VALOR:</strong>
                    <p>{Intl.NumberFormat('pt-br',{style:'currency',currency:'BRL'}).format(caso.value)}</p>
                    <p><button onClick={handleInsc} className="FaWhatsapp" to="profile/inscMyCases" >Candidatar-se</button></p>                                      


                    </li> 

                ))}                     

                </ul>
        </div>


    )
}
  • 1

    What are you using on the back? F12 or ctrl + shift + i and go on the tab console to see everything that happens from errors. Puts a console.log(response) to see what is returned from endpoint /cases.

  • I am using Node, the error that comes from the back 'Column 'cases_ids' cannot be null', is because I am not sending anything in cases_ids. but to send what I want, I need to extract the ID that is inside the <li key={case.id}>, I will try to rewrite the post to try to be a little clearer...

1 answer

2


You’re sending cases_ids: caso.id, whereas caso.id does not exist in the scope of the function and can send this id per function parameter, thus:

<button onClick={() => handleInsc(caso.id)}

and change the method to:

async function handleInsc(id) {

and when sending the ID to the back-end, puts him in the body of the requisition so:

cases_ids: id
  • 1

    That’s right. I was passing only the return of Function, being the correct function with the param... worth my noble Lucas Bittencourt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.