skip to Main Content

It shows error when it has no data in API, but I want the tbody to show a text using tr, my table has 3 rows, I want it to show a tr of a text like "no data" instead

Here’s some of my code :

    function App() {
  const [columns, setColumns] = useState([])
  const [records, setRecords] = useState([])
  const navigate = useNavigate()

  useEffect(()=>{
    axios.get('https://64dc3b32e64a8526a0f64c9f.mockapi.io/todos/')
    .then(res => {
        setColumns(Object.keys(res.data[0]))
        setRecords(res.data)
    })
  }, [])

  return(
    <div className="container mt-5">
      <div className="text-end">
        <Link to="/create" className="btn btn-primary">Add</Link>
      </div>
      <table className="table">
        <thead>
          <tr>
          <th>id</th>
          <th>name</th>
          <th>Action</th>
          </tr>
        </thead>
        <tbody>
        {
          records.map((d, i) => (
            <tr key={i}>
              <td>{d.id}</td>
              <td>{d.name}</td>             
              <td>
                <Link to={`/update/${d.id}`} className="btn btn-sm btn-success">Update</Link>
                <button onClick = {e => handleSubmit(d.id)} className="btn btn-sm ms-1 btn-danger">Delete</button>
              </td>
            </tr>
          ))
        }
        </tbody>
      </table>
    </div>
  );

2

Answers


  1. you can do like this,

    <td>{d.id ? d.id : 'no data'}</td>
    <td>{d.name ? d.name : 'no data'}</td> 
    

    or like this,

             {d ? <tr key={i}>
                  <td>{d.id}</td>
                  <td>{d.name}</td>             
                  <td>
                    <Link to={`/update/${d.id}`} className="btn btn-sm btn-success">Update</Link>
                    <button onClick = {e => handleSubmit(d.id)} className="btn btn-sm ms-1 btn-danger">Delete</button>
                  </td>
                </tr> : <tr>
                          'no data'
                      </tr>}
    
    Login or Signup to reply.
  2.  <tbody>
        {recodes.length > 0 ? <>{
          records.map((d, i) => (
            <tr key={i}>
              <td>{d.id}</td>
              <td>{d.name}</td>             
              <td>
                <Link to={`/update/${d.id}`} className="btn btn-sm btn-success">Update</Link>
                <button onClick = {e => handleSubmit(d.id)} className="btn btn-sm ms-1 btn-danger">Delete</button>
              </td>
            </tr>
          ))
        }</> : {
    <tr className="no_record text-center">
    <td col={3}>
    <h4>No Record Found</h4>
     </td>
    </tr> 
    </tbody>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search