Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/sagnikrivud/weather-chart

Weather chart details in React (V:18.0.0)
https://github.com/sagnikrivud/weather-chart

openweathermap-api react

Last synced: about 15 hours ago
JSON representation

Weather chart details in React (V:18.0.0)

Awesome Lists containing this project

README

        

![React](https://w7.pngwing.com/pngs/235/872/png-transparent-react-computer-icons-redux-javascript-others-logo-symmetry-nodejs-thumbnail.png)

This project demonstrates how to create a React application with interactive charts using react-chartjs-2 and Chart.js. It also includes functionality to fetch and display the user's current latitude and longitude using the Geo-location API.

### System requirements

- [Node(18.20.2)](https://nodejs.org/en)
- [Npm (10.5.0)](https://www.npmjs.com)
- [React(18.3.1)](https://react.dev/learn)

### Installation
```sh
$ git clone https://github.com/sagnikcapital/weather-chart.git
```
```sh
$ cd weather-chart
```
```sh
$ npm install
```
```sh
$ npm start
```

### Set Default Node and NPM version
```sh
$ nvm alias default
```

### React Chart JS
> Refer: https://react-chartjs-2.js.org/docs/migration-to-v4

### React Bootstrap
> Refer: https://react-bootstrap.netlify.app/docs/getting-started/introduction

### Open weather API
> Refer: https://openweathermap.org/api

### `Useeffects` Lifecycle hook
```js
const { useState, useEffect } = React;

const ForExample = () => {
const [name, setName] = useState("");
const [username, setUsername] = useState("");

//On load or on mount
useEffect(
() => {
console.log("effect");
},
[username]
);

//On destroy DOM
useEffect(() => {
return () => {
console.log("cleaned up");
};
}, []);

const handleName = e => {
const { value } = e.target;

setName(value);
};

const handleUsername = e => {
const { value } = e.target;

setUsername(value);
};

return (








{name}


{username}



);
};
```

```js
/**
*
*/
useEffect(() => {
/* ComponentDidMount code */
}, []);

/**
*
*/
useEffect(() => {
return () => {
/* componentWillUnmount code */
}
}, []);
/**
* we need to set at least one variable as hook's dependency
* (in this case, var1 and var2)
*/
useEffect(() => {
/* componentDidUpdate code */
}, [var1, var2]);
```
> Refer: https://stackoverflow.com/questions/55020041/react-hooks-useeffect-cleanup-for-only-componentwillunmount

> Refer: https://dev.to/prototyp/react-useeffect-explained-with-lifecycle-methods-296n

### Usestate Hook
> useState is a React Hook that lets you add a state variable to your component.
```js
import { useState } from 'react';
const myComponent = () => {
const [state, setState] = useState(initialState);
setState('This is a state');
}
```
### React Hook Form
> Refer: https://react-hook-form.com

```js
const validationConfig = {
email: {
required: 'Email is required',
pattern: {
value: /^\S+@\S+$/i,
message: 'Invalid email address',
},
},
note: {
required: 'Note is required',
},
};

const {
register,
handleSubmit,
formState: { errors },
}

/**Form control validation */


Email:

{errors.email &&
{errors.email.message}
}


Note:

{errors.note &&
{errors.note.message}
}


Send


```

### `userRef` hook
> is a React Hook that lets you reference a value.
```js
import { useRef } from 'react';

const chartRef = useRef();

const input = chartRef.current;
```

### Home Page
![Home](/public/blobs/home.png)

### Send Details
![Details](/public/blobs/send-details.png)

### Use `.env` values in Vite
```js
import.meta.env.KEY_NAME_FROM_ENV
```
```js

```
> Refer: https://vitejs.dev/guide/env-and-mode

### `useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes.
```js
const id = useId()
```
- Generating unique IDs for accessibility attributes
```js
import { useId } from 'react';

function PasswordField() {
const passwordHintId = useId();
}

<>


>
```

### React Empty tag
Apart from the regular React.Fragment syntax, there’s a very simple and easy JSX syntax available to use fragments, which is expressed by an empty JSX tag like below, This is a shorter syntax for React Fragments.
```js
<> >
```

### ``

> find common bugs in components early during development.
```js

```

### `foreachloop`
```js
let users = ['Alice', 'Bob', 'Charlie'];

let userElements = users.map(function(user) {
return

  • {user}
  • ;
    });

    // Now we can use `userElements` in JSX:
    return (


      {userElements}

    );
    ```
    > Refer: https://www.altcademy.com/blog/how-to-use-foreach-in-reactjs

    ### `useEffect` in About
    ```js
    import { useEffect } from "react";

    const [aboutValue, setAboutValue] = useState('Hi');

    useEffect(()=>{
    /**On mounted Dom*/
    setAboutValue('I am Sagnik');
    },[]);

    useEffect(() => {
    /**On destroy */
    return() => {
    setAboutValue('Cleaned up');
    };
    });
    ```

    ### Contact Us form validation using `formik`
    ```js
    import { Formik, Form, Field, ErrorMessage } from 'formik';
    import * as Yup from 'yup';

    /**Set Initial value of form fields */
    const initialValues = {
    name: '',
    email: '',
    message: '',
    phone: ''
    };
    /**Form Validation config */
    const validationSchema = Yup.object({
    name: Yup.string().required('Name is required'),
    email: Yup.string().email('Invalid email address').required('Email is required'),
    message: Yup.string().required('Message is required'),
    phone: Yup.number().required('Phone number required')
    });
    /**Form submission process */
    // const onSubmit = (values, { resetForm }) => {
    // console.log('Form data', values);
    // resetForm();
    // alert('Thank you for your message!');
    // };

    const onSubmit = async (values, { resetForm }) => {
    const baseUrl = import.meta.env.VITE_BASE_API_URL;
    const apiEndpoint = 'https://your-api-endpoint.com/contact';
    try {
    const response = await fetch(apiEndpoint, {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    },
    body: JSON.stringify(values),
    });
    if (!response.ok) {
    throw new Error('Network response was not ok');
    }
    alert('Thank you for your message!');
    resetForm();
    return false;
    const result = await response.json();
    console.log('Success:', result);
    } catch (error) {
    console.error('Error:', error);
    alert('There was an error submitting your message. Please try again later.');
    }
    };

    /**Form Template */



    Name



    Email



    Phone



    Message


    Submit


    ```

    ### `useParams` Hooks

    > URL: https::/domain/profile/{username}
    > Route:
    ```js
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    import Profile from './pages/profile/profile';


    ```

    > Profile Component
    ```js
    import { useParams } from 'react-router-dom';

    const Profile = () => {
    const { userName } = useParams();
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
    const fetchUserData = async () => {
    try {
    const response = await fetch(`http://localhost:5173/weather-chart/api/profile-details/${userName}`);
    if (!response.ok) {
    throw new Error('Network response was not ok');
    }
    const data = await response.json();
    setUser(data);
    } catch (error) {
    setError(error.message);
    } finally {
    setLoading(false);
    }
    };

    fetchUserData();
    }, [userName]);

    if (loading) {
    return

    Loading...
    ;
    }

    if (error) {
    return

    Error: {error}
    ;
    }

    if (!user) {
    return

    User not found
    ;
    }

    return (


    Profile: {user.name}


    Bio: {user.bio}


    Age: {user.age}



    );
    };

    export default Profile;
    ```

    ### 404 Not found Page
    ```js
    import NotFound from "./error/notfound"; /*Template page component*/

    /*Other Routes*/
    } />
    ```

    ### `useContext` Hook for to read and subscribe to context.
    ```js
    import { createContext, useContext } from 'react';

    export const ThemeContext = createContext();
    const theme = useContext(ThemeContext);

    /**Component code */
    return (

    {children}

    );
    /**Component code */
    ```

    ### Use Navigation
    > Example
    ```js
    import { useNavigate } from 'react-router-dom';

    const HomeButton = () => {
    let history = useNavigate();

    const handleHistory = () => {
    history("/"); /**Navigate to Home */
    }

    return (

    Home

    );
    }
    ```

    ### React Events
    | | | |
    |------------------|------------------|------------------|
    | 1. onFocus | 2. onClick | 3. onChange |
    | 4. onInput | 5. onSubmit | 6. onInvalid |
    | 7. onReset | 8. onLoad | 9. onContextMenu |
    | 10. onDrag | 11. onMouseMove | 12. onMouseEnter |

    ### Children append Component

    ```js
    const ChildButton = ({message, children}) => {
    return (
    alert(message)}>{children}
    );
    }

    export default ChildButton;
    ```
    > Usage
    ```js
    import ChildButton from '../components/childbutton';

    Click Me!

    ```

    ### Auth Guard Example
    > Route or App Component
    ```js

    import React, { useState } from 'react';
    import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

    function App() {
    const[isAutheticated, setisAutheticated] = useState(false);

    /**Login Attempt */
    function login(){
    setisAutheticated(true);
    console.log("loggedInUser:" + isAutheticated)
    }

    /**Logout Attempt */
    function logout(){
    setisAutheticated(false);
    console.log("loggedInUser:" + isAutheticated)
    }
    return (





    • Link to Home Page




    • Link to Protected Page




    • Link to Unprotected Page



    Login


    Logout






    );
    }

    export default App;
    ```
    > Auth Guarded utils or helper
    ```js
    import React from 'react';
    import { Route, Redirect } from "react-router-dom";

    const GuardedRoute = ({ component: Component, auth, ...rest }) => (
    (
    auth === true
    ?
    :
    )} />
    )

    export default GuardedRoute;
    ```
    > Now Import this Helper to App
    ```js

    ```
    - Refer: https://romik-mk.medium.com/authguard-react-router-v6-764f049e172d
    - Refer: https://blog.netcetera.com/how-to-create-guarded-routes-for-your-react-app-d2fe7c7b6122
    - Refer: https://ui.dev/react-router-protected-routes-authentication

    ### `useLocation` Hook
    > The useLocation hook returns the location object from the current URL, which includes the following:
    pathname: This is the path of the URL.
    search: This is the query string (?) included in the URL.
    hash: This is the result of the hash fragment (#) from the URL.

    ```js
    import { useLocation } from "react-router-dom";

    const location = useLocation();

    console.log(location);
    ```
    ```sh
    {
    pathname: ‘/products/school/’, search: ‘?bags’, hash: ‘’,
    state: undefined}hash: “”pathname: “/products/school/”
    search: “?bags”state: undefined“
    }
    ```
    - Refer: https://www.educative.io/answers/how-to-use-the-uselocation-hook-in-react

    ### Swagger Documentation
    - URL: http://localhost:5173/api-docs
    - Page
    ![Home](/public/blobs/swagger.png)

    > Setup
    ```sh
    $ npm install swagger-ui-react swagger-ui
    ```
    > Source
    ```js
    import SwaggerUI from 'swagger-ui-react';
    import 'swagger-ui-react/swagger-ui.css';

    const SwaggerUIComponent = () => {
    return (




    );
    };

    export default SwaggerUIComponent;
    ```