Fetching data from local json file - javascript

I have a problem with the module not being found in React import. Here is my API from the file:
[
{
"poolNumber": "1",
"sender": "Damir",
"notRoutedReason": "NumberDoesntExist",
"sentDateTime": "2019-08-13T08:01:48.1535075Z",
"requestedDeliveryReportMaskText": "Submitted",
"deliveryReportReceivedDateTime": "2019-08-13T08:01:48.1535075Z",
"isUnicode": "FALSE",
"messageUUID": "4889e632-a314-45e2-89fd-35b07b4f9ff2"
},
{
"poolNumber": "1",
"sender": "Damir",
"notRoutedReason": "NumberDoesntExist",
"sentDateTime": "2019-08-13T08:01:46.3254032Z",
"requestedDeliveryReportMaskText": "Submitted",
"deliveryReportReceivedDateTime": "2019-08-13T08:01:46.3254032Z",
"isUnicode": "FALSE",
"messageUUID": "7f48626f-7dfe-4772-99e6-3a4c1df15e0e"
}
]
And then I'm trying to call it under imports so I can log(data)..
import React from 'react'
import dataJSON from './data.json'
const getData = async () => {
const response = await fetch(dataJSON)
const data = await response;
return getData
}
But I can't fetch data coz it isn't getting module I need.
How can I fix this?

If you're using Create React App this should work fine :
import dataJSON from './data.json'
console.log(dataJSON )

You could use axios / Promise based HTTP client for the browser and node.js to handle the request in the React componentDidMount life-cycle method.
https://github.com/axios/axios
But I agree that in CreatReactApp is easier to just:
import info from './data.json';

If you are using create-react-app, just import
import dataJson from './dataJson.json';
Please see my sandbox import json in react app

Tnx all for trying to help me, but my solution was putting .json file in public folder, and importing it in App.js... that Way engine didn't trow error and I resolved it with async/await.

For use import and export statements, you have to use es6, and for this, babal is required.
Maybe you have to add babel-plugin-import to your project: read if you have and how to install and configure here here)

Related

Installing Plaiceholder in Next.js / Webpack 5 causes: Module not found: Can't resolve 'child_process'

I'm building on Next.js app and when I install / import Plaiceholder (for generating placeholder images), I get the following error: Module not found: Can't resolve 'child_process'
Node v14.18.0
Next.js v11.1.2
Plaiceholder v2.2.0
Sharp v0.29.2
I understand this error message to mean that webpack5 is trying to bundle node packages that aren't available to the client. But I'm not clear why it is doing this. I haven't customized any of the webpack configs, and I can't find any mention of this issue in the Plaiceholder docs. How do I fix it?
NOTE: I want the base64 data URL to get created during the build, so that it available as soon as the page loads (not fetched asynchronously at run time).
Here's my next.config.js
module.exports = {
reactStrictMode: true,
};
My package.json only has scripts, dependencies, and devDependencies (nothing to change module resolution)
In case it's relevant, here's a simplified example using Plaiceholder:
import Image from "next/image";
import { getPlaiceholder } from "plaiceholder";
import React, { useState } from "react";
...
const { base64 } = await getPlaiceholder(imgUrl);
...
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
It seems like plaiceholder is not suitable for client-side rendering. I believe that package is for the Node.js environment. That's why you get this error when you try to render your component on the client side.
To solve this problem, you need to move import { getPlaiceholder } from 'plaiceholder' to the NextJS API section. Then you can call that API with your URL data in the body. Then get the base64.
/api/getBase64.js
import { getPlaiceholder } from "plaiceholder";
export default async (req, res) => {
const { body } = req;
const { url } = body;
const { base64 } = getPlaiceholder(url);
res.status(200).send(base64);
};
/component.js
import Image from "next/image";
import React, { useState, useEffect } from "react";
const [base64, setBase64] = useState()
useEffect(() => {
(async () => {
const _base64 = await fetch.post('/api/getBase64', {url: imgUrl}); // wrote for demonstration
setBase64(_base64);
})()
})
return (<Image
src={imgUrl}
placeholder="blur"
blurDataURL={base64}
/>);
I know blurDataURL will be undefined until you fetch the data but this is the way how you can use plaiceholder library to manage your images. It should be imported only for the NodeJS environment. If you do not like this approach, you can try to find another library that also works for the browser environment (client)
UPDATED according to the comment:
If you want to generate this base64 at build time, you can use getStaticProps in the pages that use this Image component. NextJS is smart enough to understand which libraries are used in the client-side or server-side. So you can do this:
import { getPlaiceholder } from "plaiceholder"; // place it at the root of file. This will not be bundled inside of client-side code
export async function getStaticProps(context) {
const { base64 } = await getPlaiceholder(imgUrl);
return {
props: { base64 }, // will be passed to the page component as props
}
}
This way, by using getStaticProps, the page will be created at build time. You can get the base64 prop inside of the page that uses the image component and pass that prop to blurDataURL. Also, you can use this approach with getServerSideProps too.
This is from NextJS website:
Note: You can import modules in top-level scope for use in
getServerSideProps. Imports used in getServerSideProps will not be
bundled for the client-side.
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
It's necessary to Install plugin for Next Js dependency and configure next config based on Plaiceholder Docs for using getPlaiceholder() function in getStaticProps like the answer by #oakar.
npm i #plaiceholder/next
const { withPlaiceholder } = require("#plaiceholder/next");
module.exports = withPlaiceholder({
// your Next.js config
});

'Cannot read property 'apps' of undefined' in nuxtJs/ firebase

I have tried to integrate firebase with Nuxt Js and i am getting this error
As per documentation first I have installed firebase with help of "npm install firebase" and then i have installed "npm install #nuxtjs/firebase" and third i have integrated my firebase config in modules in nuxt.config.js
so whats the solution to solve the above error?
Thanks in advance
It depends on which version of #nuxtjs/firebase you are using, because this package #nuxtjs/firebase is not compatible with firebase version 9+ supporting tree-shaking.
So you need to downgrade you package to firebase version 8 and prior.
For more information, please check the authors github issues.
If you are using the new Modular SDK v9.0.1 you might get the above error as it does not use firebase. namespace now,
Try using getApps() instead of firebase.apps.
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
const firebaseConfig = {...}
if (!getApps().length) {
//....
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app) export {db, auth}
I banged my head against this problem for a while - I was trying to use the Realtime Database in a dynamic page and getting the same error. I finally went back to this issue on the firebase module repo. Basically I had to do two things:
use the async asyncData method instead of just defining data properties; and
use both the app and params variables.
So instead of this:
export default {
data: () => ({
items: []
)},
async fetch ({ params }) {
const ref = this.$fire.database.ref(`foo/${params.slug}`)
const data = (await ref.once('value')).val()
this.items = data
}
}
I had to do this:
export default {
async asyncData ({ app, params }) {
const ref = app.$fire.database.ref(`foo/${params.slug}`)
const data = (await ref.once('value')).val()
return { items: data }
}
}

It give me error while importing axios from node module

I have installed axios via npm and try to import axios to my front end script file.
The error which i am facing is
Uncaught SyntaxError: Cannot use import statement outside a module
This is my app.js file
import axios from 'axios';
function updateRecipt(items) {
axios.post('/update-reciept',items).then(res=>{
console.log(res);
})
}
Note:I also change "type":"tag" to "type":"module" in axios package.json and import statement to const axios = require("../../node_module/axios"). but it doesnot work for me
You are using CommonJS.
To import axios you could do
const axios = require("axios");
Instead if you want to use ES Modules,
you need to go to package.jsonand add "type": "module", (you could also add "type": "commonjs", to use explicitly CommonJS)
You're using the es6 syntax instead of the commonJS. Try using this
const axios = require('axios');
If you want to use es6, you'll need something like Babel
Try putting that in another file, then do this:
const axios = require('your_file.js');
then go back to your file, and add:
import axios from 'axios';
module.exports = axios

ReactJS - Importing store breaks Jest

I had a file with one function that creates an axiosInstance, it used to look like this:
import Axios from 'axios';
import getToken from '#/api/auth-token';
const [apiUrl] = [window.variables.apiUrl];
export const createApiInstance = () => {
return Axios.create({
baseURL: `${apiUrl}`,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});
};
Something we wanted to implement was notifying the user when their JWT token expires (so they won't unwittingly continue using the app while all of their requests are returning 401s). My solution turned this file into this:
import Axios from 'axios';
import getToken from '#/api/auth-token';
import store from '#/main.jsx';
import { userActionCreators } from '#/store/action-creators';
const [apiUrl] = [window.variables.apiUrl];
export const createApiInstance = (urlExtension = '') => {
const axiosInstance = Axios.create({
baseURL: `${apiUrl + urlExtension}`,
headers: {
Authorization: `Bearer ${getToken()}`,
},
});
axiosInstance.interceptors.response.use(response => {
if (response.status === 401)
store.dispatch(userActionCreators.setUserTokenExpired());
return response;
});
return axiosInstance;
};
This worked very well, as now all of the responses from the API are being checked for a 401 Unauthorized status and dispatching an action so the app can respond to it.
Jest doesn't like the import store, so 95% of the tests in the app fail when the store is imported here. I'm certain it is the importing of the store because every test passes when it is commented it.
I've had absolutely no luck getting anything to work.
I've tried updating setting jest and babel-jest to the same versions, setting react, react-dom, and react-test-renderer to the same versions. I've looked into configuring moduleNameMapper to mock the store in the jest config in package.json but I'm not sure how to make that work. I'm starting to consider taking a completely different approach to this problem such as applying middleware to check for 401 responses instead, but I'm worried I'll end up running into the same issue after a bunch of work.
The problem with mocking the store in the test files themselves is that there's hundreds of test files in this large application, so literally anything besides adding mocking to each individual file is the solution I'm looking for.
If anyone else is having this problem, this occurred because I was exporting the store from the same file as my ReactDOM.render. Apparently you can export from this file but as soon as you try to import what is exported somewhere else it will catch it and break tests. The solution is to create and export the store from a different file.
Make sure you have a .babelrc file, as jest doesn't understand the context of babel and JSX files otherwise. Related Stack Qusetion
If that doesn't quite do the trick can you update with the main.jsx code and let me know then i'll update

Reading data.json with HttpClient on Stackblitz?

I have a tiny demo and it attempts to read app/data.json using the Angular HttpClient.
const post$:Observable<Post> = <Observable<Post>> http.get('./data.json');
However the HttpClient reponse says:
Failure during parsing ...
Thoughts?
Stackblitz currently doesn't serve static files except the case when they are in assets folder.
So you have two options here:
1) Import json directly as module
import data from './data.json';
console.log(data) // => {title: "Simulating HTTP Requsts", content: "This is off the hook!!"}
For more details See other answers
2) Move that json in assets folder(Note: you have to reload stackblitz to
make it working):
http.get('/assets/data.json')
Forked Stackblitz
Currently, you can't get the JSON directly over HTTP, but you can import it instead
data.json
it returns resource of index.html instead of the data you expected
online example
import { of } from 'rxjs';
import data from './data.json';
export class AppComponent {
constructor(http:HttpClient) {
}
ngOnInit(){
const post$ = of(data);
post$.subscribe(console.log);
}
}
i think there are some issues about reading local json in stackblitz it doesn't return plain json just the index.html instead. but another way is mocking a request from local json, you can try:
import data from './data.json'
ngOnInit(){
this.getDatas().subscribe(data=>{
console.log(data)
})
}
getDatas():Observable<any>{
return of(data).pipe(delay(1000));
}
forked DEMO

Categories

Resources