React POST selected <li> item's ID

Viewed 300

I want to get clicked <li> item's ID and POST this value with Fetch. I don't know how to handle with it. I'm waiting your help.

I explained my codes on this pic. Basically i can list all users list inside <li> item. It works! But i need to get clicked item's "user.id" and save into a state like "setClickedUser". Then POST this ID with Fetch.

Description

const [username, setUsername] = useState([]);
const [conversatid, setConversatId] = useState([]);

useEffect(()=>{
    
  fetch('http://localhost:8000/api/current_user/', {
    headers: {
      Authorization: `JWT ${localStorage.getItem('token')}`
    }
  })
    .then(res => res.json())
    .then(json => {
      setUsername(json.id);
    });

},[]) 

const convcreate = (e, data, kullanici) => {

  fetch('http://localhost:8000/api/conversat/', {
    method: 'POST',
    headers: {
      Authorization: `JWT ${localStorage.getItem('token')}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({User1i: username, User2ii: clickeduser,})
  })
    .then(res => res.json())
    .then(json => {
      setConversatId(json.id);
    }); };

  const alluClicked = user => evt => {

    /// GET CLICKED USER'S ID AND SAVE INTO "clickeduser"

  }

    return (
        <div className="kullist">
                { props.allusers2 && props.allusers22.map( user => {
                return (

                    <li key={user.id} onClick={alluClicked} className="tumtekkul">

  
                                <a> {user.username} </a>


                    </li> );  })} </div> ) }
2 Answers

You may do:

const alluClicked = userId => {
  // SAVE userId where you need
}

return (
  <div className="kullist">
  {props.allusers2 && props.allusers22.map(user => {
    return (
      <li key={user.id} onClick={() => alluClicked(user.id)} className="tumtekkul">

I've solve that issue. I hope it will help another one.

  const alluClicked = userId => {
    
    fetch('http://localhost:8000/api/conversat/', {
    method: 'POST',
    headers: {
      Authorization: `JWT ${localStorage.getItem('token')}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({User1i: username, User2ii: userId,})
  })
    .then(res => res.json())
    .then(json => {
      setConversatId(json.id);
    });

  }
Related