Query Strings with React for a small weather app - javascript

I want to be able to set a city for my weather app using query-strings like ?latt_long=34.052235,-118.243683&&woeid=2442047. Here is a link to it https://github.com/rushingMarina/weather-react-app . Right now I have a cities.json file in my project and App.js fetches data about the cities from there. I can not seem to figure out how to use query-strings. On https://www.npmjs.com/package/query-string it tells me to use const queryString = require('query-string'); in order to use query-strings but I can not declare a const in my App.js.
My App.js:
import React, { Component } from "react";
import FrontSide from "./FrontSide";
import BackSide from "./BackSide";
import "./panel.css";
import cities from "./cities.json"
import queryString from 'query-string';
class App extends Component {
const queryString = require('query-string'); //I get unexpected token error (11:6) on this line right before queryString
console.log(location.search);
state = {flipped: false, currentCity: cities[0]};
onFlip =() => {
this.setState({flipped: !this.state.flipped});
};
onSelectCity = (city) => {
this.setState({currentCity: city})
}
render() {
return (
<div className={`panel ${this.state.flipped ? 'flip' : ""}`}>
<div className="panel-front">
<FrontSide onClick={this.onFlip} currentCity={this.state.currentCity}/>
</div>
<div className="panel-back">
<BackSide
cities={cities}
onClick={this.onFlip}
currentCity={this.state.currentCity}
onSelect={this.onSelectCity}
/>
</div>
</div>
);
}
}
export default App;
My cities.json
[
{
"title":"Los Angeles",
"location_type":"City",
"woeid":2442047,
"latt_long":"34.052235,-118.243683"
},
{
"title":"San Diego",
"location_type":"City",
"woeid":2487889,
"latt_long":"32.715736,-117.161087"
},
{
"title":"New York",
"location_type":"City",
"woeid":2459115,
"latt_long":"40.730610,-73.935242"
},
{
"title":"Chicago",
"location_type":"City",
"woeid":2459115,
"latt_long":"41.881832,-87.623177"
},
{"title":"St Petersburg",
"location_type":"City",
"woeid":2123260,
"latt_long":"59.932739,30.306721"
}
]
i tried declaring
const queryString = require('query-string');
but react shows unexpected token at "queryString"
Please refer to my github link, there you will find App.js and cities.json files
I expect to get information about the city to display on my FrontSide from URL query-string like.
This is the error I am getting:
Failed to compile.
./src/App.js
Syntax error: Unexpected token (11:6)
9 | class App extends Component {
10 |
> 11 | const queryString = require('query-string');
| ^
12 | console.log(location.search);
13 |
14 | state = {flipped: false, currentCity: cities[0]};

Just remote the const queryString = require('query-string'); line out of the class declaration and put it on top. Just right below the import statements and everything should work fine. React doesn't like require statements inside the class declaration

Related

Undefined after console are homepage to see if we getting correct the data in inspect element [Solved]

The detail of the problem is that I'm not getting the data we expected within our code. We have set up the following to see within our project folder.
Within webpack.config.js we set up resolve.alias in the webpack configuration, so we can include it in the resolve object of the webpack config file.
This is the file:
module.exports = {
// other webpack config options
resolve: {
alias: {
// Create an alias for the queries folder
queries: path.resolve(__dirname, 'src/queries'),
},
},
};
This is what are path name will look like:
import { homeQuery } from "queries/navigation/homeLinks";
Created a webpack.config.js.
Console.log are data of homeData and HomeData.homelink.
Tested the query within GraphQL Playground in Hygraph.
From there I checked the console in the browser.
I have found out we are not getting the query in our body that we want but we have tested the query within GraphQL Playground. We have found out that we correctly getting the correct query that we want to get into our data within console.log.
This is a query for the homepage:
import { gql } from "#apollo/client";
export const homeQuery = gql`
query homeLinks {
pages(
where: {id: "clbzl7ovpe64d0ak5qh7o2p8f", slug: "Home"}
stage: PUBLISHED
locales: en
) {
id
slug
title
}
}`
;
This where we console are data for the homepage:
console.log(homeData && homeData?.homeLink?.pages);
console.log(homeData)
import React from 'react';
import '../assets/style/navigation.css';
import { useQuery } from '#apollo/client';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import { homeQuery } from "../queries/navigation/homeLinks";
import { logoassetsQuery } from "../queries/navigation/logoLinks";
export default function App() {
const { loading: logoAssetsLoading, error: logoassetsData } = useQuery(logoassetsQuery);
//This is query for the pages.
const { loading: homeLoading, error: homeError, data: homeData } = useQuery(homeQuery);
//This is for front-end error message.
if (logoAssetsLoading) return <p>Loading Logo Assets...</p>;
if (homeLoading) return <p>Loading... this page links.</p>
if (homeError) return <p>Error :( this page don't work.</p>;
// Debugging step 1: Check the value of data.navigation
console.log(homeData && homeData.homeLinks)
console.log(homeData)
// Debugging step 2: Check the value of data
//console.log(data);
return (
<div className='navigation'>
<div className='full_width_container'>
<div className='wrapper'>
<Router>
<React.Fragment>
<nav>
<div className='nav_groups logo'>
{homeData && homeData?.homeLinks?.pages && homeData?.homeLinks?.page(link => (
<li key={link?.id}>
<Link to={`/${link?.slug}`}>
<img src={logoassetsData?.logoAssets} alt='main logo'/>
</Link>
</li>
))}
</div>
</nav>
</React.Fragment>
</Router>
</div>
</div>
</div>
);
}

How do I import framer-motion using dynamic import in NextJS?

I working with framer-motion in my NextJS project. I'm trying to import {motion} using Next's dynamic import. But unfortunately, it doesn't seem to work.
import { motion } from "framer-motion"
I'm trying to convert the above import as a dynamic import as given below:
const motion = dynamic(() =>
import("framer-motion").then((module) => module.motion)
)
But it throws an error :
"Argument of type '() => Promise<ComponentClass<never, any> | FunctionComponent<never> | { default: ComponentType<never>; } | ((<Props>(Component: string | ComponentType<Props>, customMotionComponentConfig?: CustomMotionComponentConfig | undefined) => CustomDomComponent<...>) & HTMLMotionComponents & SVGMotionComponents)>' is not assignable to parameter of type 'DynamicOptions<{}> | Loader<{}>'."
Whenever I import other things like icons, custom components it works as expected, for example the dynamic import given below works fine :
const DoubleArrowRightIcon = dynamic(() => import("#radix-ui/DoubleArrowRightIcon"), {
loading: () => <p>..</p>,
})
I have looked at other answers and found this link but still, not able to make it work.
Any help please?

How to use 'env' property in Nuxt.js to get newapi?

I try to make news web apps to use newsapi.org.
I wanted to hide my api_key so I decided to use env property in Nuxt.Js.
But now I got 401 status code from server.
first of all, I made the .env file in project file and I put my API_KEY.
and then I installed 'dotenv' use 'yarn add dotenv' command in VSCode terminal.
and I add nuxt.config.ts file. I have used TypeScript in my project so all file depend on TypeScript.
require('dotenv').config()
const { API_KEY } = process.env
export default {
~~~~~~~~~~
env: {
API_KEY,
},
}
and I used Vuex to get news information.
so I made code like following.
~/store/getNews.ts
import { MutationTree, ActionTree, GetterTree } from "vuex";
import axios from "axios";
const url = 'http://newsapi.org/v2/top-headlines';
interface RootState { }
export interface NewsArticles {
source?: {}
author?: string
title?: string
description?: string
url?: any
urlToImage?: any
publishedAt?: string
content?: string
}
interface State {
newArticle: NewsArticles
}
export const state = () => ({
newsArticle: []
})
export const getters: GetterTree<State, RootState> = {
newsArticle: (state: State) => state.newArticle
}
export const mutations: MutationTree<State> = {
setNewsArticle: (state: State, newsArticle: NewsArticles) => {
state.newArticle = newsArticle
}
}
export const actions: ActionTree<State, RootState> = {
getNewsArticle: async ({ commit },{params}) => {
try{
const data = await axios.get(url,{params})
commit('setNewsArticle', data.data.articles)
}catch(error){
commit('setNewsArticle',[])
}
}
}
export default { state, getters, mutations, actions }
and finally, I made vue file to show the news information like following.
<template>
<div>
<p>this is NewsApi test pages!!</p>
<ul v-for="(item, index) in items" :key="index">
<li>{{ item.title }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { NewsArticles } from '~/store/getNews'
const getNews = namespace('getNews')
#Component({})
export default class extends Vue {
#getNews.Action getNewsArticle!: Function
#getNews.Getter newsArticle!: NewsArticles
items: any = []
async mounted() {
await this.getNewsArticle({
params: { country: 'jp', category: 'business', apiKey: process.env.API_KEY },
})
this.items = this.newsArticle
}
}
</script>
I ran my app but I got 401 status code and I checked the console error like following.
{status: "error", code: "apiKeyInvalid",…}
code: "apiKeyInvalid"
message: "Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."
status: "error"
I don't know why that error occurred.
I checked apikey correctly setting to confirm consle.log.
in index.vue
<script lang='ts'>
~~~~
export default class extend Vue{
mounted(){
console.log(process.env.API_KEY)
}
}
</script>
You don't need to call require('dotenv').config(), as Nuxt automatically invokes it.
Also, for the env vars to be available in the production build, their names must be prefixed with NUXT_ENV_ (i.e., NUXT_ENV_API_KEY). Note this allows you to keep the key from being checked into source (assuming your .env file is also kept out of source control), but your API key can still be observed in the Network tab in DevTools.

How to access Object array file into react component?

I am trying to access an object array file within src folder eg: data.js(Object array only) this file into my app.js(react component)
in first scenario 1.I have tried this problem using react in
src--[app.js(component)/data.js(object array)].
When I was run it shows me an error like
(TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function)means null array/undefined.
in second scenarios 2. when I add object array in app.js within the same page its shows me perfect result. without an error but trying from another file like data.js it taking null array I have used to stringify() and JSON parser but no result
Object array file data.js ->
const datas=[
{
"id":"1",
"firstname":"sam",
"lastname":"parkar"
},
{
"id":"2",
"firstname":"julee",
"lastname":"fransic"
}
];
react component app.js ->
import React from 'react';
import datas from './data';
import DataInfo from './DataInfo';
function App () {
const appdata=datas.map( inner => inner.id + inner.firstname + inner.lastname)
//print on console
console.log(appdata)
return (
<div className="App">
<p>App js page</p>
{appdata}
</div>
)
}
export default App;
error ->
TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function
21 | return (
22 |
23 |
> 24 | <div className="App">
| ^ 25 |
26 | <p>App js page</p>
actual result:-
App js page
1samparkar2juleefransic
and on console
(2) ["1samparkar", "2juleefransic"]
0: "1samparkar"
1: "2juleefransic"
Make sure you export the datas correctly
export const datas=[
{
"id": "1",
"firstname": "sam",
"lastname": "parkar"
},
{
"id": "2",
"firstname": "julee",
"lastname": "fransic"
}
];
And in app.js call it like this:
import {datas} from './data';
You can use JSON file like this:
datas.json
[
{
"id":"1",
"firstname":"sam",
"lastname":"parkar"
},
{
"id":"2",
"firstname":"julee",
"lastname":"fransic"
}
]
In app.js:
import datas from './datas.json';
If you are using JSON file then save that file as datas.json
Now in your app.js file use <datas/> instead of {datas}.
you can use {datas} when you are using it in a jsx attribute. for example-
<textarea name="JSON" value={datas} />.
but in your case, you should use <datas />.

Import static JSON data in React

I am trying to load static JSON data to my react app. But, it wan't allow me to load data.
I am using webpack version 4.26.1
It shows me following error:
SyntaxError: src/data/movieData.json: Unexpected token, expected ; (2:10)
1 | {
2 | "data": [
| ^
3 | {
4 | "id": 1,
5 | "title": "Freed",
My Code:
data/jsonResponse.json
{
"data": [
{
"id": 1,
"title": "Freed"
},
{
"id": 2,
"title": "Fifty"
}
]
}
main.js
import React, { Component } from 'react';
import Content from './Content';
import jsonResponse from './data/jsonResponse.json';
class Main extends Component {
render() {
return (
<div className="main">
<Content item={ jsonResponse } />
</div>
);
}
}
export default Main;
Content.js
import React from 'react';
const Content = () => {
const movies = this.props.item.data;
return (
movies.map(movie => {
return (
<span >{movie.title}</span>
);
})
)
}
export default Content;
Edited:
If i use js instead of JSON like:
const movies_data = {
"data": [
{
"id": 1,
"title": "Freed"
},
{
"id": 2,
"title": "Fifty"
}
]
}
export default movies_data;
and in Main.js file
import jsonResponse from './data/movieData';
Then in browser it shows following error.
Cannot read property 'props' of undefined
There are 2 workarounds for loading json files in a js file.
Rename your json file to .js extension and export default your json from there.
Since json-loader is loaded by default on webpack >= v2.0.0 there's no need to change your webpack configs.
But you need to load your json file as json!./data/jsonResponse.json (pay attention to json!)
EDIT:
Cannot read property 'props' of undefined
The reason you're getting this error is because you're trying to access this on a functional component!
Answer regarding edited question and Cannot read property 'props' of undefined error
You can't access this in functional components. props are passed as argument to functional components so please try this (Content.js file):
import React from 'react';
const Content = (props) => {
const movies = props.item.data;
return (
movies.map(movie => {
return (
<span >{movie.title}</span>
);
})
)
}
export default Content;
You have to add a JSON loader to import json files.
You need to check if in your Webpack config if exist an loader to JSON.
I recommend to use this loader.
https://www.npmjs.com/package/json-loader

Categories