I am trying to create a download link in a React front end where the user will be clicking a button and a file will be downloaded.
To acheive this, I am trying to pass the file path inside a JS function and inside the function I want to call an API endpoint with that path, and the api will return me the file.
Now, for some reason, the code I am writing is not working. Kindly help me to rectify my mistake.
import React, { useState, useEffect } from "react";
import axios from "axios";
import moment from "moment";
import {
Grid,
Paper,
Typography,
Table,
TableCell,
TableContainer,
TableHead,
TableRow,
TableBody,
} from "@mui/material";
import Download from './Download';
import FileDownload from "js-file-download";
export default function Classroomtest() {
const uid = localStorage.getItem("uniqueid");
const [assignments, setassignments] = useState("");
useEffect(() => {
axios
.get(`http://localhost:5000/api/v1/app/get-my-assignments/${uid}`)
.then((res) => {
setassignments(res.data);
});
}, []);
const view = (path) =>{
//Nothing is coming here
}
return (
<Grid>
<Paper
sx={{
padding: 3,
margin: 1,
}}
>
<TableContainer
component={Paper}
sx={{
margin: "10px",
width: "97%",
}}
>
<Table sx={{ minWidth: 100 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell align="right">Topic</TableCell>
<TableCell align="right">Due</TableCell>
<TableCell align="right">Action</TableCell>
<TableCell align="right">Delete</TableCell>
</TableRow>
</TableHead>
{assignments?.data?.myassignments.map((item) => (
<TableBody key={item._id}>
<TableCell align="right">{item.assignmentname}</TableCell>
<TableCell align="right">{moment.utc(item.duedate).format("MMMM,DD")}</TableCell>
<TableCell align="right">
<button type="button" onClick={view(item.assignmentfilepath)}>Download</button>
</TableCell>
<TableCell align="right">Java</TableCell>
</TableBody>
))}
</Table>
</TableContainer>
</Paper>
</Grid>
);
}
Example of a file path returned is : uploads\user-1638470921415.pdf