skip to Main Content
 import React, { useState } from "react";
    import Papa from "papaparse";
    
    function App() {
      const [file, setFile] = useState();
      const [array, setArray] = useState([]);
      const [predictions, setPredictions] = useState([]);
    
      const fileReader = new FileReader();
    
      const handleOnChange = (e) => {
        setFile(e.target.files[0]);
         Papa.parse(e.target.files[0], {
         header: true,
         skipEmptyLines: true,
         complete: function (results) {
           console.log(results.data)
         },
       });    
      };
            
 
         
    
      const csvFileToArray = (string) => {
        Papa.parse(string, {
          header: true,
          skipEmptyLines: true,
          complete: function (results) {
            //console.log('Parsing Results:', results);
            if (Array.isArray(results.data)) {
              const parsedArray = results.data.map((row) => {
                const obj = {};
                for (let key in row) {
                  obj[key.trim()] = row[key].trim();
                }
                return obj;
              });
              setArray(parsedArray);
            } else {
              console.error('Error parsing CSV data.');
            }
          },  
        });
      };
      
      
      const handleOnSubmit = (e) => {
        e.preventDefault();
    
        if (file) {
          fileReader.onload = function (event) {
            const text = event.target.result;
            csvFileToArray(text);
          };
    
          fileReader.readAsText(file); 
        }
      };

const handlePredict = async (event) => {
        console.log('array',array) 
        event.preventDefault()
        try { 
          const response = await fetch('/multi_airpredict', {                                                                                             
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(array),
          });
    
          if (!response.ok) {
            throw new Error('Prediction failed');
          }
    
    
          const data = await response.json();
          setPredictions(data.predictions);
        } catch (error) {
          console.log(error);
        } 
      };
    
      const headerKeys = Object.keys(Object.assign({}, ...array));
    
      return (
        <div style={{ textAlign: 'center' }}>    
          <h1>CSV IMPORT</h1> 
          <form>
            <input
              type="file"
              id="csvFileInput"
              accept=".csv"
              onChange={handleOnChange}
            />
    
            <button onClick={handleOnSubmit}>IMPORT CSV</button>
    
            <button onClick={handlePredict}>PREDICT</button>
          </form>
    
          <br />
    
          <table>
            <thead>
              <tr key="header">
                {headerKeys.map((key) => (
                  <th key={key}>{key}</th>
                ))}
              </tr>
            </thead>
    
           <tbody>
              {array.map((item, index) => (
                <tr key={index}>
                  {Object.values(item).map((val, index) => (
                    <td key={index}>{val}</td>
                  ))}
                </tr>  
              ))}
            </tbody> 
                  </table>
    
                    
          <div>
            <h2>Predictions</h2>
            <ul>
              {predictions.map((prediction, index) => (
                <li key={index}>{prediction}</li>
              ))}
              </ul>
             
         
    
          </div>
        </div>
      );
    }
    
    export default App; 

This is a project which takes a csv file, converts it to array and give to the prediction model to print predictions for all rows together. I am still still working on the flask api part which can accept whole csv as input. so i think this error is happening because currently there are no predicted values present. still if anyone can help to solve this?

2

Answers


  1. Chosen as BEST ANSWER
            import React, { useState } from "react";
        import Papa from "papaparse";
        
        function App() {
          const [file, setFile] = useState();
          const [array, setArray] = useState([]);
          const [predictions, setPredictions] = useState([]);
        
          const fileReader = new FileReader();
        
          const handleOnChange = (e) => {
            setFile(e.target.files[0]);
             Papa.parse(e.target.files[0], {
             header: true,
             skipEmptyLines: true,
             complete: function (results) {
               console.log(results.data)
             },
           });    
          };
                
     
             
        
          const csvFileToArray = (string) => {
            Papa.parse(string, {
              header: true,
              skipEmptyLines: true,
              complete: function (results) {
                //console.log('Parsing Results:', results);
                if (Array.isArray(results.data)) {
                  const parsedArray = results.data.map((row) => {
                    const obj = {};
                    for (let key in row) {
                      obj[key.trim()] = row[key].trim();
                    }
                    return obj;
                  });
                  setArray(parsedArray);
                } else {
                  console.error('Error parsing CSV data.');
                }
              },  
            });
          };
          
          
          const handleOnSubmit = (e) => {
            e.preventDefault();
        
            if (file) {
              fileReader.onload = function (event) {
                const text = event.target.result;
                csvFileToArray(text);
              };
        
              fileReader.readAsText(file); 
            }
          };
    
    const handlePredict = async (event) => {
            console.log('array',array) 
            event.preventDefault()
            try { 
              const response = await fetch('/multi_airpredict', {                                                                                             
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify(array),
              });
        
              if (!response.ok) {
                throw new Error('Prediction failed');
              }
        
        
              const data = await response.json();
              setPredictions(data.predictions);
            } catch (error) {
              console.log(error);
            } 
          };
        
          const headerKeys = Object.keys(Object.assign({}, ...array));
        
          return (
            <div style={{ textAlign: 'center' }}>    
              <h1>CSV IMPORT</h1> 
              <form>
                <input
                  type="file"
                  id="csvFileInput"
                  accept=".csv"
                  onChange={handleOnChange}
                />
        
                <button onClick={handleOnSubmit}>IMPORT CSV</button>
        
                <button onClick={handlePredict}>PREDICT</button>
              </form>
        
              <br />
        
              <table>
                <thead>
                  <tr key="header">
                    {headerKeys.map((key) => (
                      <th key={key}>{key}</th>
                    ))}
                  </tr>
                </thead>
        
               <tbody>
                  {array.map((item, index) => (
                    <tr key={index}>
                      {Object.values(item).map((val, index) => (
                        <td key={index}>{val}</td>
                      ))}
                    </tr>  
                  ))}
                </tbody> 
                      </table>
        
                        
              <div>
                <h2>Predictions</h2>
                <ul>
                  {predictions.map((prediction, index) => (
                    <li key={index}>{prediction}</li>
                  ))}
                  </ul>
                 
             
        
              </div>
            </div>
          );
        }
        
        export default App; 
    

    this is complete code


  2. Please provide more info to your question.

    With the given information, I can infer the predictions is still null at the moment when is called so try to do some validation before to make sure that function finish to fetch

    like this

    const predictions = await getinDatafromSVG()
    if (!predictions) retrun <>loading</>
    return  <ul> {predictions.map((prediction, index) => ( <li key={index}>{prediction}</li> ))} </ul>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search