|
1 |
| -import React from 'react'; |
2 |
| -import { Question } from './questiontable'; |
| 1 | +import React from "react"; |
| 2 | +import { Question } from "./questiontable"; |
| 3 | +import axios from 'axios'; |
3 | 4 |
|
4 | 5 | interface UploadFileProps {
|
5 | 6 | setQuestions: React.Dispatch<React.SetStateAction<Question[]>>;
|
6 | 7 | }
|
7 | 8 |
|
| 9 | +export interface JSONQuestion { |
| 10 | + title: string; |
| 11 | + description: string; |
| 12 | + categories: string; |
| 13 | + complexity: string; |
| 14 | + link: string; |
| 15 | +} |
| 16 | + |
8 | 17 | const UploadFile: React.FC<UploadFileProps> = ({ setQuestions }) => {
|
9 | 18 | const handleUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
10 | 19 | const file = event.target.files?.[0];
|
11 | 20 | if (file) {
|
12 | 21 | const reader = new FileReader();
|
13 | 22 | reader.onload = (e) => {
|
14 | 23 | const content = e.target?.result;
|
15 |
| - if (typeof content === 'string') { |
| 24 | + console.log("content is ", content); |
| 25 | + if (typeof content === "string") { |
16 | 26 | try {
|
17 |
| - const jsonQuestions: Question[] = JSON.parse(content); |
18 |
| - setQuestions((prevQuestions) => [...prevQuestions, ...jsonQuestions]); |
| 27 | + const jsonQuestions: JSONQuestion[] = JSON.parse(content)["questions"]; |
| 28 | + console.log("json questions are ", jsonQuestions); |
| 29 | + for (let i = 0; i < jsonQuestions.length; i++) { |
| 30 | + try { |
| 31 | + const questionData = { |
| 32 | + "title": jsonQuestions[i]["title"], |
| 33 | + "description": jsonQuestions[i]["description"], |
| 34 | + "link": jsonQuestions[i]["link"], |
| 35 | + "category": jsonQuestions[i]["categories"], |
| 36 | + "difficulty": jsonQuestions[i]["categories"] |
| 37 | + } |
| 38 | + const response = await axios.post('http://localhost:3000/questions', questionData); |
| 39 | + console.log('Question created successfully:', response.data); |
| 40 | + } catch (error) { |
| 41 | + console.error('Error creating question:', error); |
| 42 | + } |
| 43 | + |
| 44 | + } |
| 45 | + |
| 46 | + // setQuestions((prevQuestions) => [ |
| 47 | + // ...prevQuestions, |
| 48 | + // ...jsonQuestions, |
| 49 | + // ]); |
19 | 50 | } catch (error) {
|
20 |
| - alert('Error parsing JSON: ' + error); |
| 51 | + alert("Error parsing JSON: " + error); |
21 | 52 | }
|
22 | 53 | }
|
23 | 54 | };
|
|
0 commit comments