On Click of a button make an API call and show the response

25 Views Asked by At

I have an array of objects I am intreating that response I want on click of Read More button it will make an API call and display the result of the response and Read More button should not show for that record same way for other cases also.

I am able to iterate the stockNewsData in the UI I want when i will click Read More it will make an API call with the mapped record sr_no as parameter of the API and show the result of the response and Read More button should not show for the clicked record

const stockNewsData =  [
        {
            "sr_no": 230580390285.0,
            "caption": "Cochin Shiptard123"
        },
        {
            "sr_no": 230460390173.0,
          "caption": "Cochin Shiptard456" 
        },
        {
            "sr_no": 230540390285.0,
            "caption": "Cochin Shiptard789"
        },
        {
            "sr_no": 230430390173.0,
            "caption": "Cochin Shiptard345511" 
        }
];
const getDetailedNews = async (sr_no) => {
    try {
      const res = await axios.get(`${CMOTS_URL}/Company-News-Details/${sr_no}`);
         console.log(res);
    } catch (err) {
      console.log("err", err);
    }
};
<div className="news">
  {stockNewsData.map((item) => (
   <div className="newsbox">
    <h4>{item?.caption}</h4>
    <p onClick={() => getDetailedNews(item.sr_no)}>Read More</p>
    <p>need to display the response here </p>                            
    </div>
  ))}
</div>
1

There are 1 best solutions below

0
Ozmen Celik On

try this if i get u correct.

import React, { useState } from 'react';
import axios from 'axios';

const stockNewsData = [
  {
    "sr_no": 230580390285.0,
    "caption": "Cochin Shiptard123"
  },
  {
    "sr_no": 230460390173.0,
    "caption": "Cochin Shiptard456"
  },
  {
    "sr_no": 230540390285.0,
    "caption": "Cochin Shiptard789"
  },
  {
    "sr_no": 230430390173.0,
    "caption": "Cochin Shiptard345511"
  }
];

const getDetailedNews = async (sr_no, setNewsData) => {
  try {
    const res = await axios.get(`${CMOTS_URL}/Company-News-Details/${sr_no}`);
    setNewsData(prevState => ({
      ...prevState,
      [sr_no]: res.data // Store response data with sr_no as key
    }));
  } catch (err) {
    console.log("err", err);
  }
};

const NewsComponent = () => {
  const [newsData, setNewsData] = useState({}); // State to store detailed news data

  return (
    <div className="news">
      {stockNewsData.map((item) => (
        <div className="newsbox" key={item.sr_no}>
          <h4>{item?.caption}</h4>
          {newsData[item.sr_no] ? (
            <div>
              <p>{newsData[item.sr_no]}</p> {/* Display response data */}
            </div>
          ) : (
            <p onClick={() => getDetailedNews(item.sr_no, setNewsData)}>Read More</p>
          )}
        </div>
      ))}
    </div>
  );
};

export default NewsComponent;