Fetching data from local .json file in react.js returns multiple errors





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I have a json file named autofill.json and it's created to autofill a search bar when pressed on.



the autofill.json is a test file that's why it looks like this.



        [
{
"a": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
}
},
"b": {
"box": {
"name": "apple",
"href": "https://www.berserk.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
]





The .json file is then fetched in the file named FetchAndParseResults.js

    import fetch from 'isomorphic-fetch'

const FetchAndParseResults = (url) => {
return fetch(url).then(response => {
const parsedJson = response.json()
return parsedJson
})
}

export default FetchAndParseResults





The data that gets fetched is used in searchcontainer.js where everything gets placed in, the search etc.

    import React from 'react'
import Searchbar from './index.js'
import FetchAndParseResults from './FetchAndParseResults.js'

class SearchContainer extends React.Component {
state = {
results:
}

performSearch = event => {
return FetchAndParseResults('static/autofill.json').then(data => {
this.setState({ results: data })
})
}

render () {
console.log('performSearch event', this.performSearch)
console.log('data inside performSearch', this.state.results)
return (
<Searchbar
performSearch={this.performSearch}
results={this.state.results}
/>
)
}
}

export default SearchContainer





Then to map through the data that is in autofill.json there is a file named autofill.js

    import React from 'react'
import PropTypes from 'prop-types'
import Styles from './searchbar.scss'

const AutoFill = (props) => {
console.log('proppppppsss', props)
const results = props.results ||

return (
<ul className={Styles.searchUl}>
{results.map(({ name, href }) => (
<li className={Styles.searchLi} key={href}>
<a className={Styles.searchA} href={href} target='_blank' rel='noopener noreferrer' key={href}>
{name}
</a>
</li>
))}
</ul>
)
}

AutoFill.propTypes = {
results: PropTypes.array
}

export default AutoFill





the Searchbar component in (index.js) that is being used in searchcontainer.js

import React from 'react'
import Styles from './searchbar.scss'
import Icon from '../../components/icon/icon'
import Search from '../../components/form-input/search'
import AutoFill from './autofill'
import PropTypes from 'prop-types'

export default class Searchbar extends React.Component {
constructor (props) {
super(props)
this.state = {
className: Styles.input,
icon: Styles.icon__wrapper,
value:
}
this.input = React.createRef()
}

openInput = () => {
this.setState({
className: Styles.input__active,
icon: Styles.iconWidth
}, () => {
this.input.focus()
})
this.props.onOpen && this.props.onOpen()
}

closeInput = () => {
this.setState({
className: Styles.input,
icon: Styles.icon__wrapper
})
this.props.onClose && this.props.onClose()
}

handleChange = event => {
let value = event.target.value
this.setState({ value })
this.props.performSearch(value)
}

handleSubmit = event => {
event.preventDefault()
}

render () {
console.log('results', this.props.results)
console.log('state.value', this.state.value)
return (
<div>
<form onSubmit={this.handleSubmit} className={Styles.search}>
<div className={this.state.icon}>
<Icon className={Styles.icon__wrapper} iconName='faSearch' onClick={this.openInput} />
</div>
<Search autoComplete='off' value={this.state.value} onChange={this.handleChange} id='search' tabIndex='0' myref={input => { this.input = input }} className={this.state.className} onBlur={this.closeInput} placeholder='Search' />
</form>
<div>
<AutoFill results={this.props.results} />
</div>
</div>
)
}
}

Search.propTypes = {
performSearch: PropTypes.func,
results: PropTypes.array
}





When i try to refer to a what is in the json file from the search i receive the error,


GET http://localhost:3000/[object%20Object] 404 (Not Found)




And




about:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON
at position 0




The second error is fixed by doing



const parsedJson = response.text(


instead of



const parsedJson = response.json()


to get more information where/what the error takes place. But by doing this i receive the error,




searchcontainer.js:12 Uncaught (in promise) TypeError: Cannot read property 'results' of undefined






I've tried to run it from npm build instead of running it in a dev environment which didn't fix it.



I read that a mock url should work but then again i want to acces it from a file and not from a url?



Any help would be highly appreciated and looked into.










share|improve this question































    2















    I have a json file named autofill.json and it's created to autofill a search bar when pressed on.



    the autofill.json is a test file that's why it looks like this.



            [
    {
    "a": {
    "apple": {
    "name": "apple",
    "href": "https://www.apple.com/"
    },
    "armadillo": {
    "name": "armadillo",
    "href": "https://www.armadillo.com/"
    }
    },
    "b": {
    "box": {
    "name": "apple",
    "href": "https://www.berserk.com/"
    },
    "berserk": {
    "name": "berserk",
    "href": "https://www.berserk.com/"
    }
    }
    }
    ]





    The .json file is then fetched in the file named FetchAndParseResults.js

        import fetch from 'isomorphic-fetch'

    const FetchAndParseResults = (url) => {
    return fetch(url).then(response => {
    const parsedJson = response.json()
    return parsedJson
    })
    }

    export default FetchAndParseResults





    The data that gets fetched is used in searchcontainer.js where everything gets placed in, the search etc.

        import React from 'react'
    import Searchbar from './index.js'
    import FetchAndParseResults from './FetchAndParseResults.js'

    class SearchContainer extends React.Component {
    state = {
    results:
    }

    performSearch = event => {
    return FetchAndParseResults('static/autofill.json').then(data => {
    this.setState({ results: data })
    })
    }

    render () {
    console.log('performSearch event', this.performSearch)
    console.log('data inside performSearch', this.state.results)
    return (
    <Searchbar
    performSearch={this.performSearch}
    results={this.state.results}
    />
    )
    }
    }

    export default SearchContainer





    Then to map through the data that is in autofill.json there is a file named autofill.js

        import React from 'react'
    import PropTypes from 'prop-types'
    import Styles from './searchbar.scss'

    const AutoFill = (props) => {
    console.log('proppppppsss', props)
    const results = props.results ||

    return (
    <ul className={Styles.searchUl}>
    {results.map(({ name, href }) => (
    <li className={Styles.searchLi} key={href}>
    <a className={Styles.searchA} href={href} target='_blank' rel='noopener noreferrer' key={href}>
    {name}
    </a>
    </li>
    ))}
    </ul>
    )
    }

    AutoFill.propTypes = {
    results: PropTypes.array
    }

    export default AutoFill





    the Searchbar component in (index.js) that is being used in searchcontainer.js

    import React from 'react'
    import Styles from './searchbar.scss'
    import Icon from '../../components/icon/icon'
    import Search from '../../components/form-input/search'
    import AutoFill from './autofill'
    import PropTypes from 'prop-types'

    export default class Searchbar extends React.Component {
    constructor (props) {
    super(props)
    this.state = {
    className: Styles.input,
    icon: Styles.icon__wrapper,
    value:
    }
    this.input = React.createRef()
    }

    openInput = () => {
    this.setState({
    className: Styles.input__active,
    icon: Styles.iconWidth
    }, () => {
    this.input.focus()
    })
    this.props.onOpen && this.props.onOpen()
    }

    closeInput = () => {
    this.setState({
    className: Styles.input,
    icon: Styles.icon__wrapper
    })
    this.props.onClose && this.props.onClose()
    }

    handleChange = event => {
    let value = event.target.value
    this.setState({ value })
    this.props.performSearch(value)
    }

    handleSubmit = event => {
    event.preventDefault()
    }

    render () {
    console.log('results', this.props.results)
    console.log('state.value', this.state.value)
    return (
    <div>
    <form onSubmit={this.handleSubmit} className={Styles.search}>
    <div className={this.state.icon}>
    <Icon className={Styles.icon__wrapper} iconName='faSearch' onClick={this.openInput} />
    </div>
    <Search autoComplete='off' value={this.state.value} onChange={this.handleChange} id='search' tabIndex='0' myref={input => { this.input = input }} className={this.state.className} onBlur={this.closeInput} placeholder='Search' />
    </form>
    <div>
    <AutoFill results={this.props.results} />
    </div>
    </div>
    )
    }
    }

    Search.propTypes = {
    performSearch: PropTypes.func,
    results: PropTypes.array
    }





    When i try to refer to a what is in the json file from the search i receive the error,


    GET http://localhost:3000/[object%20Object] 404 (Not Found)




    And




    about:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON
    at position 0




    The second error is fixed by doing



    const parsedJson = response.text(


    instead of



    const parsedJson = response.json()


    to get more information where/what the error takes place. But by doing this i receive the error,




    searchcontainer.js:12 Uncaught (in promise) TypeError: Cannot read property 'results' of undefined






    I've tried to run it from npm build instead of running it in a dev environment which didn't fix it.



    I read that a mock url should work but then again i want to acces it from a file and not from a url?



    Any help would be highly appreciated and looked into.










    share|improve this question



























      2












      2








      2








      I have a json file named autofill.json and it's created to autofill a search bar when pressed on.



      the autofill.json is a test file that's why it looks like this.



              [
      {
      "a": {
      "apple": {
      "name": "apple",
      "href": "https://www.apple.com/"
      },
      "armadillo": {
      "name": "armadillo",
      "href": "https://www.armadillo.com/"
      }
      },
      "b": {
      "box": {
      "name": "apple",
      "href": "https://www.berserk.com/"
      },
      "berserk": {
      "name": "berserk",
      "href": "https://www.berserk.com/"
      }
      }
      }
      ]





      The .json file is then fetched in the file named FetchAndParseResults.js

          import fetch from 'isomorphic-fetch'

      const FetchAndParseResults = (url) => {
      return fetch(url).then(response => {
      const parsedJson = response.json()
      return parsedJson
      })
      }

      export default FetchAndParseResults





      The data that gets fetched is used in searchcontainer.js where everything gets placed in, the search etc.

          import React from 'react'
      import Searchbar from './index.js'
      import FetchAndParseResults from './FetchAndParseResults.js'

      class SearchContainer extends React.Component {
      state = {
      results:
      }

      performSearch = event => {
      return FetchAndParseResults('static/autofill.json').then(data => {
      this.setState({ results: data })
      })
      }

      render () {
      console.log('performSearch event', this.performSearch)
      console.log('data inside performSearch', this.state.results)
      return (
      <Searchbar
      performSearch={this.performSearch}
      results={this.state.results}
      />
      )
      }
      }

      export default SearchContainer





      Then to map through the data that is in autofill.json there is a file named autofill.js

          import React from 'react'
      import PropTypes from 'prop-types'
      import Styles from './searchbar.scss'

      const AutoFill = (props) => {
      console.log('proppppppsss', props)
      const results = props.results ||

      return (
      <ul className={Styles.searchUl}>
      {results.map(({ name, href }) => (
      <li className={Styles.searchLi} key={href}>
      <a className={Styles.searchA} href={href} target='_blank' rel='noopener noreferrer' key={href}>
      {name}
      </a>
      </li>
      ))}
      </ul>
      )
      }

      AutoFill.propTypes = {
      results: PropTypes.array
      }

      export default AutoFill





      the Searchbar component in (index.js) that is being used in searchcontainer.js

      import React from 'react'
      import Styles from './searchbar.scss'
      import Icon from '../../components/icon/icon'
      import Search from '../../components/form-input/search'
      import AutoFill from './autofill'
      import PropTypes from 'prop-types'

      export default class Searchbar extends React.Component {
      constructor (props) {
      super(props)
      this.state = {
      className: Styles.input,
      icon: Styles.icon__wrapper,
      value:
      }
      this.input = React.createRef()
      }

      openInput = () => {
      this.setState({
      className: Styles.input__active,
      icon: Styles.iconWidth
      }, () => {
      this.input.focus()
      })
      this.props.onOpen && this.props.onOpen()
      }

      closeInput = () => {
      this.setState({
      className: Styles.input,
      icon: Styles.icon__wrapper
      })
      this.props.onClose && this.props.onClose()
      }

      handleChange = event => {
      let value = event.target.value
      this.setState({ value })
      this.props.performSearch(value)
      }

      handleSubmit = event => {
      event.preventDefault()
      }

      render () {
      console.log('results', this.props.results)
      console.log('state.value', this.state.value)
      return (
      <div>
      <form onSubmit={this.handleSubmit} className={Styles.search}>
      <div className={this.state.icon}>
      <Icon className={Styles.icon__wrapper} iconName='faSearch' onClick={this.openInput} />
      </div>
      <Search autoComplete='off' value={this.state.value} onChange={this.handleChange} id='search' tabIndex='0' myref={input => { this.input = input }} className={this.state.className} onBlur={this.closeInput} placeholder='Search' />
      </form>
      <div>
      <AutoFill results={this.props.results} />
      </div>
      </div>
      )
      }
      }

      Search.propTypes = {
      performSearch: PropTypes.func,
      results: PropTypes.array
      }





      When i try to refer to a what is in the json file from the search i receive the error,


      GET http://localhost:3000/[object%20Object] 404 (Not Found)




      And




      about:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON
      at position 0




      The second error is fixed by doing



      const parsedJson = response.text(


      instead of



      const parsedJson = response.json()


      to get more information where/what the error takes place. But by doing this i receive the error,




      searchcontainer.js:12 Uncaught (in promise) TypeError: Cannot read property 'results' of undefined






      I've tried to run it from npm build instead of running it in a dev environment which didn't fix it.



      I read that a mock url should work but then again i want to acces it from a file and not from a url?



      Any help would be highly appreciated and looked into.










      share|improve this question
















      I have a json file named autofill.json and it's created to autofill a search bar when pressed on.



      the autofill.json is a test file that's why it looks like this.



              [
      {
      "a": {
      "apple": {
      "name": "apple",
      "href": "https://www.apple.com/"
      },
      "armadillo": {
      "name": "armadillo",
      "href": "https://www.armadillo.com/"
      }
      },
      "b": {
      "box": {
      "name": "apple",
      "href": "https://www.berserk.com/"
      },
      "berserk": {
      "name": "berserk",
      "href": "https://www.berserk.com/"
      }
      }
      }
      ]





      The .json file is then fetched in the file named FetchAndParseResults.js

          import fetch from 'isomorphic-fetch'

      const FetchAndParseResults = (url) => {
      return fetch(url).then(response => {
      const parsedJson = response.json()
      return parsedJson
      })
      }

      export default FetchAndParseResults





      The data that gets fetched is used in searchcontainer.js where everything gets placed in, the search etc.

          import React from 'react'
      import Searchbar from './index.js'
      import FetchAndParseResults from './FetchAndParseResults.js'

      class SearchContainer extends React.Component {
      state = {
      results:
      }

      performSearch = event => {
      return FetchAndParseResults('static/autofill.json').then(data => {
      this.setState({ results: data })
      })
      }

      render () {
      console.log('performSearch event', this.performSearch)
      console.log('data inside performSearch', this.state.results)
      return (
      <Searchbar
      performSearch={this.performSearch}
      results={this.state.results}
      />
      )
      }
      }

      export default SearchContainer





      Then to map through the data that is in autofill.json there is a file named autofill.js

          import React from 'react'
      import PropTypes from 'prop-types'
      import Styles from './searchbar.scss'

      const AutoFill = (props) => {
      console.log('proppppppsss', props)
      const results = props.results ||

      return (
      <ul className={Styles.searchUl}>
      {results.map(({ name, href }) => (
      <li className={Styles.searchLi} key={href}>
      <a className={Styles.searchA} href={href} target='_blank' rel='noopener noreferrer' key={href}>
      {name}
      </a>
      </li>
      ))}
      </ul>
      )
      }

      AutoFill.propTypes = {
      results: PropTypes.array
      }

      export default AutoFill





      the Searchbar component in (index.js) that is being used in searchcontainer.js

      import React from 'react'
      import Styles from './searchbar.scss'
      import Icon from '../../components/icon/icon'
      import Search from '../../components/form-input/search'
      import AutoFill from './autofill'
      import PropTypes from 'prop-types'

      export default class Searchbar extends React.Component {
      constructor (props) {
      super(props)
      this.state = {
      className: Styles.input,
      icon: Styles.icon__wrapper,
      value:
      }
      this.input = React.createRef()
      }

      openInput = () => {
      this.setState({
      className: Styles.input__active,
      icon: Styles.iconWidth
      }, () => {
      this.input.focus()
      })
      this.props.onOpen && this.props.onOpen()
      }

      closeInput = () => {
      this.setState({
      className: Styles.input,
      icon: Styles.icon__wrapper
      })
      this.props.onClose && this.props.onClose()
      }

      handleChange = event => {
      let value = event.target.value
      this.setState({ value })
      this.props.performSearch(value)
      }

      handleSubmit = event => {
      event.preventDefault()
      }

      render () {
      console.log('results', this.props.results)
      console.log('state.value', this.state.value)
      return (
      <div>
      <form onSubmit={this.handleSubmit} className={Styles.search}>
      <div className={this.state.icon}>
      <Icon className={Styles.icon__wrapper} iconName='faSearch' onClick={this.openInput} />
      </div>
      <Search autoComplete='off' value={this.state.value} onChange={this.handleChange} id='search' tabIndex='0' myref={input => { this.input = input }} className={this.state.className} onBlur={this.closeInput} placeholder='Search' />
      </form>
      <div>
      <AutoFill results={this.props.results} />
      </div>
      </div>
      )
      }
      }

      Search.propTypes = {
      performSearch: PropTypes.func,
      results: PropTypes.array
      }





      When i try to refer to a what is in the json file from the search i receive the error,


      GET http://localhost:3000/[object%20Object] 404 (Not Found)




      And




      about:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON
      at position 0




      The second error is fixed by doing



      const parsedJson = response.text(


      instead of



      const parsedJson = response.json()


      to get more information where/what the error takes place. But by doing this i receive the error,




      searchcontainer.js:12 Uncaught (in promise) TypeError: Cannot read property 'results' of undefined






      I've tried to run it from npm build instead of running it in a dev environment which didn't fix it.



      I read that a mock url should work but then again i want to acces it from a file and not from a url?



      Any help would be highly appreciated and looked into.







      json reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 27 '18 at 14:26







      Drarula

















      asked Nov 22 '18 at 14:11









      DrarulaDrarula

      95




      95
























          3 Answers
          3






          active

          oldest

          votes


















          0














          The problem is most likely in the fetch call. If you look at the error message GET http://localhost:3000/[object%20Object] 404 (Not Found)
          You can see that it is trying to append an object to the URL localhost:3000/.



          You are getting the Unexpected token < in JSON at position 0 error because the response of your fetch request is probably a 404 page. The < is most likely the first char of <html>






          share|improve this answer
























          • Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

            – Drarula
            Nov 22 '18 at 14:38













          • Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

            – user2073973
            Nov 22 '18 at 14:58











          • Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

            – Drarula
            Nov 22 '18 at 15:01



















          0














          To access the JSON object in your React files, you can simply do an importation like so;



          import * as autofillData from 'autofill.json';


          It will be returned as a JSON object.



          I believe you are using the isomorphic-fetch package wrongly, if you look at their source code, https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L5 , they are accepting a URL to make a call to the API URL which will return a promise or a JSON object depending on the implementation of the API that you are calling.



          If you were to dive deeper into the open-source code here (https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L8) , you will notice that isomorphic-fetch package is using another package node-fetch to do their fetch call, which accepts the API URL and the method request options to call the API with. (As stated here; https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34)



          To continue with your test, perhaps this might be the solution you'd prefer?



          import fetch from 'isomorphic-fetch';
          import * as autofillData from 'autofill.json'; //test data

          const FetchResults = event => {
          return fetch('/https://jsonplaceholder.typicode.com/todos/1'') //mockURL, to be replaced with real API
          .then(response => {
          // const parsedJson = response.json(); // TODO: un-comment this line when the real API url is usable
          const parsedJson = autofillData; // TODO: remove this line when mocking is done and the real API URL is ready
          return parsedJson;
          })
          }

          export default FetchResults;


          To have a mock URL placeholder, I would suggest https://jsonplaceholder.typicode.com/ to prevent your fetch result to return an unexpected error during test mocking.



          Hope this is helpful.






          share|improve this answer
























          • I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

            – Drarula
            Nov 22 '18 at 15:53











          • Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

            – claireckc
            Nov 22 '18 at 16:10











          • Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

            – Drarula
            Nov 22 '18 at 21:21











          • Check what is in your data

            – claireckc
            Nov 23 '18 at 0:28











          • When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

            – Drarula
            Nov 23 '18 at 8:03



















          0














          The question has been solved, The main issue was with defining const names such as const results = which should've been const results = props.results || .



          The code has been updated incase you have problems aswell.






          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432825%2ffetching-data-from-local-json-file-in-react-js-returns-multiple-errors%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            The problem is most likely in the fetch call. If you look at the error message GET http://localhost:3000/[object%20Object] 404 (Not Found)
            You can see that it is trying to append an object to the URL localhost:3000/.



            You are getting the Unexpected token < in JSON at position 0 error because the response of your fetch request is probably a 404 page. The < is most likely the first char of <html>






            share|improve this answer
























            • Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

              – Drarula
              Nov 22 '18 at 14:38













            • Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

              – user2073973
              Nov 22 '18 at 14:58











            • Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

              – Drarula
              Nov 22 '18 at 15:01
















            0














            The problem is most likely in the fetch call. If you look at the error message GET http://localhost:3000/[object%20Object] 404 (Not Found)
            You can see that it is trying to append an object to the URL localhost:3000/.



            You are getting the Unexpected token < in JSON at position 0 error because the response of your fetch request is probably a 404 page. The < is most likely the first char of <html>






            share|improve this answer
























            • Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

              – Drarula
              Nov 22 '18 at 14:38













            • Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

              – user2073973
              Nov 22 '18 at 14:58











            • Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

              – Drarula
              Nov 22 '18 at 15:01














            0












            0








            0







            The problem is most likely in the fetch call. If you look at the error message GET http://localhost:3000/[object%20Object] 404 (Not Found)
            You can see that it is trying to append an object to the URL localhost:3000/.



            You are getting the Unexpected token < in JSON at position 0 error because the response of your fetch request is probably a 404 page. The < is most likely the first char of <html>






            share|improve this answer













            The problem is most likely in the fetch call. If you look at the error message GET http://localhost:3000/[object%20Object] 404 (Not Found)
            You can see that it is trying to append an object to the URL localhost:3000/.



            You are getting the Unexpected token < in JSON at position 0 error because the response of your fetch request is probably a 404 page. The < is most likely the first char of <html>







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '18 at 14:34









            user2073973user2073973

            348418




            348418













            • Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

              – Drarula
              Nov 22 '18 at 14:38













            • Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

              – user2073973
              Nov 22 '18 at 14:58











            • Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

              – Drarula
              Nov 22 '18 at 15:01



















            • Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

              – Drarula
              Nov 22 '18 at 14:38













            • Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

              – user2073973
              Nov 22 '18 at 14:58











            • Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

              – Drarula
              Nov 22 '18 at 15:01

















            Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

            – Drarula
            Nov 22 '18 at 14:38







            Yes that's what i was thinking but i'm refering to a file so why does it append to a url? <br> For reason i changed response.json() to response.text() to look further into the error what it exactly means than it says that results in searchcontainer.js is not a function.

            – Drarula
            Nov 22 '18 at 14:38















            Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

            – user2073973
            Nov 22 '18 at 14:58





            Do you have more calls to fetch? The one in your file fetchresults.js makes a call to static/mockData/autofill.json, but the error in your question looks different

            – user2073973
            Nov 22 '18 at 14:58













            Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

            – Drarula
            Nov 22 '18 at 15:01





            Oh, i tried to refer it to a url but then i had issues with creating a mock url in react ill edit that right now it should be, 'autofill.json'

            – Drarula
            Nov 22 '18 at 15:01













            0














            To access the JSON object in your React files, you can simply do an importation like so;



            import * as autofillData from 'autofill.json';


            It will be returned as a JSON object.



            I believe you are using the isomorphic-fetch package wrongly, if you look at their source code, https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L5 , they are accepting a URL to make a call to the API URL which will return a promise or a JSON object depending on the implementation of the API that you are calling.



            If you were to dive deeper into the open-source code here (https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L8) , you will notice that isomorphic-fetch package is using another package node-fetch to do their fetch call, which accepts the API URL and the method request options to call the API with. (As stated here; https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34)



            To continue with your test, perhaps this might be the solution you'd prefer?



            import fetch from 'isomorphic-fetch';
            import * as autofillData from 'autofill.json'; //test data

            const FetchResults = event => {
            return fetch('/https://jsonplaceholder.typicode.com/todos/1'') //mockURL, to be replaced with real API
            .then(response => {
            // const parsedJson = response.json(); // TODO: un-comment this line when the real API url is usable
            const parsedJson = autofillData; // TODO: remove this line when mocking is done and the real API URL is ready
            return parsedJson;
            })
            }

            export default FetchResults;


            To have a mock URL placeholder, I would suggest https://jsonplaceholder.typicode.com/ to prevent your fetch result to return an unexpected error during test mocking.



            Hope this is helpful.






            share|improve this answer
























            • I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

              – Drarula
              Nov 22 '18 at 15:53











            • Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

              – claireckc
              Nov 22 '18 at 16:10











            • Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

              – Drarula
              Nov 22 '18 at 21:21











            • Check what is in your data

              – claireckc
              Nov 23 '18 at 0:28











            • When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

              – Drarula
              Nov 23 '18 at 8:03
















            0














            To access the JSON object in your React files, you can simply do an importation like so;



            import * as autofillData from 'autofill.json';


            It will be returned as a JSON object.



            I believe you are using the isomorphic-fetch package wrongly, if you look at their source code, https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L5 , they are accepting a URL to make a call to the API URL which will return a promise or a JSON object depending on the implementation of the API that you are calling.



            If you were to dive deeper into the open-source code here (https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L8) , you will notice that isomorphic-fetch package is using another package node-fetch to do their fetch call, which accepts the API URL and the method request options to call the API with. (As stated here; https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34)



            To continue with your test, perhaps this might be the solution you'd prefer?



            import fetch from 'isomorphic-fetch';
            import * as autofillData from 'autofill.json'; //test data

            const FetchResults = event => {
            return fetch('/https://jsonplaceholder.typicode.com/todos/1'') //mockURL, to be replaced with real API
            .then(response => {
            // const parsedJson = response.json(); // TODO: un-comment this line when the real API url is usable
            const parsedJson = autofillData; // TODO: remove this line when mocking is done and the real API URL is ready
            return parsedJson;
            })
            }

            export default FetchResults;


            To have a mock URL placeholder, I would suggest https://jsonplaceholder.typicode.com/ to prevent your fetch result to return an unexpected error during test mocking.



            Hope this is helpful.






            share|improve this answer
























            • I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

              – Drarula
              Nov 22 '18 at 15:53











            • Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

              – claireckc
              Nov 22 '18 at 16:10











            • Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

              – Drarula
              Nov 22 '18 at 21:21











            • Check what is in your data

              – claireckc
              Nov 23 '18 at 0:28











            • When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

              – Drarula
              Nov 23 '18 at 8:03














            0












            0








            0







            To access the JSON object in your React files, you can simply do an importation like so;



            import * as autofillData from 'autofill.json';


            It will be returned as a JSON object.



            I believe you are using the isomorphic-fetch package wrongly, if you look at their source code, https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L5 , they are accepting a URL to make a call to the API URL which will return a promise or a JSON object depending on the implementation of the API that you are calling.



            If you were to dive deeper into the open-source code here (https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L8) , you will notice that isomorphic-fetch package is using another package node-fetch to do their fetch call, which accepts the API URL and the method request options to call the API with. (As stated here; https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34)



            To continue with your test, perhaps this might be the solution you'd prefer?



            import fetch from 'isomorphic-fetch';
            import * as autofillData from 'autofill.json'; //test data

            const FetchResults = event => {
            return fetch('/https://jsonplaceholder.typicode.com/todos/1'') //mockURL, to be replaced with real API
            .then(response => {
            // const parsedJson = response.json(); // TODO: un-comment this line when the real API url is usable
            const parsedJson = autofillData; // TODO: remove this line when mocking is done and the real API URL is ready
            return parsedJson;
            })
            }

            export default FetchResults;


            To have a mock URL placeholder, I would suggest https://jsonplaceholder.typicode.com/ to prevent your fetch result to return an unexpected error during test mocking.



            Hope this is helpful.






            share|improve this answer













            To access the JSON object in your React files, you can simply do an importation like so;



            import * as autofillData from 'autofill.json';


            It will be returned as a JSON object.



            I believe you are using the isomorphic-fetch package wrongly, if you look at their source code, https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L5 , they are accepting a URL to make a call to the API URL which will return a promise or a JSON object depending on the implementation of the API that you are calling.



            If you were to dive deeper into the open-source code here (https://github.com/matthew-andrews/isomorphic-fetch/blob/master/fetch-npm-node.js#L8) , you will notice that isomorphic-fetch package is using another package node-fetch to do their fetch call, which accepts the API URL and the method request options to call the API with. (As stated here; https://github.com/bitinn/node-fetch/blob/master/src/index.js#L34)



            To continue with your test, perhaps this might be the solution you'd prefer?



            import fetch from 'isomorphic-fetch';
            import * as autofillData from 'autofill.json'; //test data

            const FetchResults = event => {
            return fetch('/https://jsonplaceholder.typicode.com/todos/1'') //mockURL, to be replaced with real API
            .then(response => {
            // const parsedJson = response.json(); // TODO: un-comment this line when the real API url is usable
            const parsedJson = autofillData; // TODO: remove this line when mocking is done and the real API URL is ready
            return parsedJson;
            })
            }

            export default FetchResults;


            To have a mock URL placeholder, I would suggest https://jsonplaceholder.typicode.com/ to prevent your fetch result to return an unexpected error during test mocking.



            Hope this is helpful.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '18 at 15:32









            claireckcclaireckc

            807




            807













            • I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

              – Drarula
              Nov 22 '18 at 15:53











            • Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

              – claireckc
              Nov 22 '18 at 16:10











            • Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

              – Drarula
              Nov 22 '18 at 21:21











            • Check what is in your data

              – claireckc
              Nov 23 '18 at 0:28











            • When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

              – Drarula
              Nov 23 '18 at 8:03



















            • I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

              – Drarula
              Nov 22 '18 at 15:53











            • Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

              – claireckc
              Nov 22 '18 at 16:10











            • Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

              – Drarula
              Nov 22 '18 at 21:21











            • Check what is in your data

              – claireckc
              Nov 23 '18 at 0:28











            • When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

              – Drarula
              Nov 23 '18 at 8:03

















            I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

            – Drarula
            Nov 22 '18 at 15:53





            I've tried your method with the jsonplaceholder api not much is happening since my first fetch should also work, i assume this because i get the same error. The error: Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at searchcontainer.js:12

            – Drarula
            Nov 22 '18 at 15:53













            Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

            – claireckc
            Nov 22 '18 at 16:10





            Because there is no response field in data. In your search container component, data would be your autofill JSON value and since there is no field called response there, it would return that error.

            – claireckc
            Nov 22 '18 at 16:10













            Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

            – Drarula
            Nov 22 '18 at 21:21





            Isn't this: this.setState({ results: data.response.results }) the field where the data should be returned to?

            – Drarula
            Nov 22 '18 at 21:21













            Check what is in your data

            – claireckc
            Nov 23 '18 at 0:28





            Check what is in your data

            – claireckc
            Nov 23 '18 at 0:28













            When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

            – Drarula
            Nov 23 '18 at 8:03





            When i consolelog the data i receive, gyazo.com/f680e9ace3d2d92e6d2ce1e796c65cda It doesn't know that data.response.results is json data? Since it is returning an event.

            – Drarula
            Nov 23 '18 at 8:03











            0














            The question has been solved, The main issue was with defining const names such as const results = which should've been const results = props.results || .



            The code has been updated incase you have problems aswell.






            share|improve this answer






























              0














              The question has been solved, The main issue was with defining const names such as const results = which should've been const results = props.results || .



              The code has been updated incase you have problems aswell.






              share|improve this answer




























                0












                0








                0







                The question has been solved, The main issue was with defining const names such as const results = which should've been const results = props.results || .



                The code has been updated incase you have problems aswell.






                share|improve this answer















                The question has been solved, The main issue was with defining const names such as const results = which should've been const results = props.results || .



                The code has been updated incase you have problems aswell.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 28 '18 at 7:25

























                answered Nov 27 '18 at 14:29









                DrarulaDrarula

                95




                95






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53432825%2ffetching-data-from-local-json-file-in-react-js-returns-multiple-errors%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

                    How to change which sound is reproduced for terminal bell?

                    Can I use Tabulator js library in my java Spring + Thymeleaf project?