Home > Mobile >  React UseEffect - How to retrive selected array data and view that data
React UseEffect - How to retrive selected array data and view that data

Time:04-14

This is my JSON data File

{
    "person": [

      {
        "id": "userId",
        "sellerImage": "https://i.pravatar.cc/300",
        "lastOnline": "Date of last online",
        "sellerName": "Ryann Remo",
        "isOnline": true,
        "lastSeenDate": "Today",
        "product":"Rough Shirt",
        "messages": [
          {
            "id": "messageId",
            "userId": "userIdOfUser",
            "message": "Message text 01",
            "date": "Date of message",
            "time": "time of message",
            "isRead": false
          },
          {
            "id": "messageId",
            "userId": "userIdOfSeller",
            "message": "Message text 02",
            "date": "Date of message",
            "time": "time of message",
            "isRead": true
          },
          {
            "id": "messageId",
            "userId": "userIdOfSeller",
            "message": "Message text",
            "date": "Date of message 03",
            "time": "time of message",
            "isRead": false
          }
        ]
      },

      {
        "id": "userId",
        "sellerImage": "https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50",
        "lastOnline": "Date of last online",
        "sellerName": "Karp Bonolo",
        "isOnline": true,
        "lastSeenDate": "Yesterday",
        "product":"Rough Shirt",
        "messages": [
          {
            "id": "messageId",
            "userId": "userIdOfUser",
            "message": "Message text",
            "date": "Date of message",
            "time": "time of message",
            "isRead": false
          },
          {
            "id": "messageId",
            "userId": "userIdOfSeller",
            "message": "Message text",
            "date": "Date of message",
            "time": "time of message",
            "isRead": true
          },
          {
            "id": "messageId",
            "userId": "userIdOfSeller",
            "message": "Message text",
            "date": "Date of message",
            "time": "time of message",
            "isRead": false
          }
        ]
      }
    ]
  }

This is how I'm imported that JSON data

import AdminConversationData from "./AdminConversation.json";

const AdminConversation = () => {




  const person = AdminConversationData.person.map((data) => {
    return {
      ...data,
    };
  });

.....

This is how I'm going to select a person in react file. (Using onClick={() => setSelectPerson(idx)} I'm going to select a person here using the IDX according to the below code I need to load that person's data to another place on this page.)

<RadioGroup>
  <div className="space-y-2">
    {person.map((item, idx) => (
      <RadioGroup.Option
        key={item.id}
        value={item.id}
        onClick={() => setSelectPerson(idx)}
        className={({ active }) =>
          `${
            active
              ? 'ring-2 ring-offset-2 ring-offset-red-300 ring-white ring-opacity-60 border-l-4 border-red-500'
              : ''
          }
            relative rounded-lg shadow-md px-5 py-4 cursor-pointer flex focus:outline-none entry cursor-pointer 
            transform hover:scale-105 duration-300`
        }
        
      >
       
          <>
        <div className="flex-2">
          <div className="w-12 h-12 relative">
            <img
              className="w-12 h-12 rounded-full mx-auto"
              src={"https://picsum.photos/200"}
              alt="chat-user"
            />
            <span className="absolute w-4 h-4 bg-gray-400 rounded-full right-0 bottom-0 border-2 border-white"></span>
          </div>
        </div>
        <div className="flex-1 px-2">
          <div className="truncate w-32">
            <span className="text-gray-800">{item.sellerName}</span>
          </div>
          <div>
            <small className="text-gray-600">Yea, Sure!</small>
          </div>
        </div>
        <div className="flex-2 text-right">
          <div>
            <small className="text-gray-500">{item.lastSeenDate}</small>
          </div>
          <div>
            <small className="text-xs bg-red-500 text-white rounded-full h-6 w-6 leading-6 text-center inline-block">
              23
            </small>
          </div>
        </div>
          </>
      
      </RadioGroup.Option>
    ))}
  </div>
</RadioGroup>

(this is React headless UI radio group and I'm going to select a certain person here.)

In this place, I want to retrieve that person's data as an example the seller's name.

<>
 <div >
    <span >
       <svg width="20" height="20">
          <circle cx="8" cy="8" r="8" fill="currentColor" ></circle>
       </svg>
    </span>
 <img src="https://images.unsplash.com/photo-1549078642-b2ba4bda0cdb?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=facearea&amp;facepad=3&amp;w=144&amp;h=144" alt="" />
 </div>
 <div >
    <div >
      <span >Seller Name</span>
    </div>
    <span >Seller</span>
</div>
</>

(In here at the seller name place I want to show the selected seller name.)According to the selected person I need to load his name in the above point "Seller Name", I expect to use React UseEffect. How can I do that ?

UI : enter image description here

CodePudding user response:

You are saving just the selected id of a person. You can easily get entire object. Change the person state to receive person object and use setSelectPerson(item) instead of setSelectPerson(idx). Then, you can use any field of the object you want.

Sample example: https://codesandbox.io/s/priceless-wright-6xrn0t?file=/src/App.js

CodePudding user response:

If you have the person array and the selectPerson state variable available, you should be able to reference the seller's name like this:

<>
 <div >
    <span >
       <svg width="20" height="20">
          <circle cx="8" cy="8" r="8" fill="currentColor" ></circle>
       </svg>
    </span>
 <img src="https://images.unsplash.com/photo-1549078642-b2ba4bda0cdb?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=facearea&amp;facepad=3&amp;w=144&amp;h=144" alt="" />
 </div>
 <div >
    <div >
      <span >{person[selectPerson].sellerName}</span>
    </div>
    <span >Seller</span>
</div>
</>

Depending where your <RadioGroup> is relative to the bottom block of code you shared, you may need to lift selectPerson and setSelectPerson up to a parent.

CodePudding user response:

you dont need useEffect to do that, as said by Md Wahidul Azam in his answer you can easily get the person object ,just change your code as shown below,instead of id just set a item object

<div className="space-y-2">
{person.map((item, idx) => (
  <RadioGroup.Option
    key={item.id}
    value={item.id}
    onClick={() => setSelectPerson(item)}
    className={({ active }) =>
      `${
        active
          ? 'ring-2 ring-offset-2 ring-offset-red-300 ring-white ring-opacity-60 border-l-4 border-red-500'
          : ''
      }
        relative rounded-lg shadow-md px-5 py-4 cursor-pointer flex focus:outline-none entry cursor-pointer 
        transform hover:scale-105 duration-300`
    }
    
  >

now for I want to show the selected seller name. use the selectPerson Object as shown below in the code ,i assume both code are in same component

 <>
 <div >
<span >
   <svg width="20" height="20">
      <circle cx="8" cy="8" r="8" fill="currentColor" ></circle>
   </svg>
</span>
<img src="https://images.unsplash.com/photo-1549078642-b2ba4bda0cdb?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=facearea&amp;facepad=3&amp;w=144&amp;h=144" alt="" />
</div>
<div >
<div >
  <span >{selectPerson.sellerName}</span>
</div>
<span >Seller</span>
</div>
</>
  • Related