Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add headers to the api response using reactjs

I am new to react js,
I have a home screen with search bar. where user retrieves an employee information by providing the id. here’s the code for that.

const [firstNames, setFirstNames] = useState("");
<input
            value={name}
            type="text" 
            id="header-search"
            placeholder="Enter the search term"
            name={'id'}
            onChange={handleChange}
            />
        
        <button onClick={HandleSearch}>Search</button>

const handleChange= (e) => {
    e.preventDefault();
    setName(e.target.value);
  }

const HandleSearch = e => {

    
    e.preventDefault();
    axios.get(`http://localhost:8080/search?id=`+name)
        .then(response => {
          setLoading(false);
          if(response.status == 200 && response != null){
            
              console.log("RES",response.data);
              var tmpArray= [];
              var tmpJsx =[];
              // I was checking to see if I could retrieve the data from my response.
              var dataparse = response.data;
              var length = dataparse.length;
              console.log("length of my response array is: "+length)

              //printing the elements in array
              for (var i=0; i< length; i++){
                
                //console.log(response.data[i].firstname);
                
                 setFirstNames((firstNames) => [...firstNames, response.data[i]]);
                
              }

              
          } else{
                console.log('problem fetching');
            }
        })
        .catch(error => {
          setLoading(false);
          console.log("error occured: "+error);
        });
}

and here’s my return function:

{firstNames.map(function (names, index) {
                  return (
                    <tr key={index}>
                      <td> {names.firstname} -</td>
                      <td> {names.lastname}</td>
                    </tr>
                   )
                })}

How do I add the headers to this data.
for example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

firstname lastname
abc        abclast

i tried to put this in the map function, but then my data was looking like:

firstname lastname
abc        abclast
firstname lastname
def        deflast
firstname lastname
ghi        ghilast

Im sure there is something that im missing, could anyone help me on how to achieve this: thank you.

firstname lastname
abc        abclast
def        deflast
ghi        ghilast

>Solution :

You can do a conditional rendering by checking if the array has length greater than 0

An example would be like this. You can apply similarly to your problem

let names = [
  {firstName: 'John',lastName: 'Cena'},
  {firstName: 'Rey',lastName: 'Mysterio'},
]

const App = props => {
  return (
    <div>
      {names.length > 0 && <table> //table renders only when array has elements 
        <tbody>
        <tr>
        <th>First Name</th>   //setting headers
        <th>Last Name</th>
        </tr>
        {names.map((name,index) => {       //mapping for individual rows
          return (
            <tr key={index}>
              <td>{name.firstName}</td>
              <td>{name.lastName}</td>
            </tr>
          )
        })}
        </tbody>
      </table>}
    </div>
  );
};

codesandbox demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading