Home > Blockchain >  React.js, local json file wont display
React.js, local json file wont display

Time:03-07

I have a local json which is returning all values on console.log so I know the path is correct. However when I am trying to pull an input value of name from it, it gives me error uni.map is not a function.

What am I'm missing, any help will be fab :).

import { useState } from 'react'
import axios from 'axios'
import Uni from './Uni'

function Unis() {
    const [unis, setUnis] = useState([])
    const [query, setQuery] = useState('')

    function handleSearchQuery(e) {
        e.preventDefault()
        setQuery(e.target.value)
    }

    async function searchUnis(e) {
        e.preventDefault()
        console.log()
        var response = await axios.get(data.json)
        setUnis(response.data)
    }
    return (
        <div>
        <input value={query} onChange={handleSearchQuery} />
        <button onClick={searchUnis}>Search</button>
        <ul>
        {
            unis.map(function(i, index){
                return (
                    <li key={index}>
                        <Uni name={i.name} />
                    </li>
                )
            })
        }
        </ul>
        </div>
    )
}   
export default Unis;

data.json

{
  "data": [
    {
      "name": "xxx",
      "years": "2022"
    },
    {
      "name": "hhh",
      "years": "2021"
    }
]
}

CodePudding user response:

Good Luck,

You have used data.json directly without import.

var response = await axios.get(data.json)

Ans:

Step 1:

Import the data.json file in Unis file.

import Data from './data.json';

Step 2:

Use the data like below.

var response = await axios.get(Data.data);

CodePudding user response:

I read in the comments that data.json file is inside public folder, with that in mind, you could get it like so :

import { useState } from 'react'
import axios from 'axios'
import Uni from './Uni'

function Unis() {
    const [unis, setUnis] = useState([])
    const [query, setQuery] = useState('')

    function handleSearchQuery(e) {
        e.preventDefault()
        setQuery(e.target.value)
    }

    async function searchUnis(e) {
        e.preventDefault()
        console.log()
        var response = await axios.get("/data.json");
        setUnis(response.data.data)
    }
    return (
        <div>
        <input value={query} onChange={handleSearchQuery} />
        <button onClick={searchUnis}>Search</button>
        <ul>
        {
            unis.map(function(i, index){
                return (
                    <li key={index}>
                        <Uni name={i.name} />
                    </li>
                )
            })
        }
        </ul>
        </div>
    )
}   
export default Unis;

Reading from a json file is like reading from a REST API which responds with json.

  •  Tags:  
  • json
  • Related