Showing posts with label React. Show all posts
Showing posts with label React. Show all posts

Monday, October 31, 2022

Jest testing framework for React & Node.js

https://jestjs.io/docs/getting-started

{
"name": "project",
"version": "1.0.0",
"description": "API",
"main": "src/server.js",
"scripts": {
"test": "jest",
"test-watch": "jest --watchAll",
"start": "node src/server.js",
"watch": "nodemon src/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"csv-parse": "^5.3.1",
"express": "^4.18.2",
"morgan": "^1.10.0"
},
"devDependencies": {
"jest": "^29.2.2",
"supertest": "^6.3.1"
}
}

npm i jest --save-dev

npm i supertest --save-dev

Sunday, October 30, 2022

Run client & server in separate folders

Node.js server and React client:

"scripts": {
"install-server": "cd server && npm install",
"install-client": "cd client && npm install",
"install": "npm run install-server && npm run install-client",
"server": "cd server && npm run watch",
"client": "cd client && npm start",
"watch": "npm run server & npm run client",
"test": "echo \"Error: no test specified\" && exit 1"
},

Node.js server and React client:

"scripts": {
"install-server": "npm install --prefix server",
"install-client": "npm install --prefix client",
"install": "npm run install-server && npm run install-client",
"server": "npm run watch --prefix server",
"client": "npm start --prefix client",
"watch": "npm run server & npm run client",
"deploy": "npm run build --prefix client && npm start --prefix server",
"test": "npm test --prefix server & npm test --prefix client"
},

//

Sunday, October 23, 2022

Get unique values from array and remove duplicates

Extract unique values from arr1:

let arr1 = [1, 0, 1, 1, 2, 0, 2, 0, 2, 2];
    console.log( arr1.filter((el, i, a) => a.indexOf(el) === i) );
(3) [1, 0, 2]

 https://stackoverflow.com/questions/66527958/only-add-item-to-array-if-unique-otherwise-delete-react

https://stackoverflow.com/questions/11246758/how-to-get-unique-values-in-an-array

https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates

https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript

Create unique keys for React elements

- function to generate unique keys/ids/numbers/strings and use that

- existing npm packages like uuid, uniqid, etc

- generate random number `key-${new Date().getTime()}` with prefix from item being iterated

- using the unique ID from the database

https://stackoverflow.com/questions/39549424/how-to-create-unique-keys-for-react-elements

Add and append HTML elements in React

Append arr2 elements to arr: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

(arr) => arr.concat(gerArr2())

Append arr2 array to arr: (4) [Array(4), Array(4), Array(4), Array(4)]

(arr) => [...arr, gerArr2()]

Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate

https://javascript.plainenglish.io/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

https://www.skptricks.com/2018/06/append-or-prepend-html-using-reactjs.html

Friday, October 21, 2022

Toggle burger menu with buttons

//

const toggleClick = () => {
document.querySelector('nav').addEventListener('click', (e) => {
let parent = e.target.parentNode;
if (parent.classList.contains('logo') || parent.tagName === 'LI') {
console.log('toggle');
}
});
};

//

Thursday, October 20, 2022

Many identical console.logs in DevTools

Comment <React.StrictMode> in index.js

root.render(
// <React.StrictMode>
<App />
// </React.StrictMode>
);

After fetch console.log in React component like this:

const function = () => (
<>
{console.log(data)}
</>
);

return (function())

Before return getting {} and {data} after fetch...

Tuesday, October 18, 2022

clickHandler is not a function

Pass empty function to onClick as temporary solution:

const falseClick = () => {};

//

Can't get array length after fetch object destructuring

Cannot read properties of undefined (reading 'length'):

const { posts = [] } = data; // destructuring array from data
console.log(posts.length);

https://bobbyhadz.com/blog/javascript-cannot-read-property-length-of-undefined

const { data: { posts } = [] } = data; // extract arr didn't work out
const arr = posts || []; // empty array fallback
console.log(arr.length); // getting error in React

In React console.log after fetch like this:

const postsData = () => (
<>
{console.log(posts.length)}
</>
);
return (postsData());

https://leocode.com/development/how-to-deal-with-async-await-in-the-array-functions/

Monday, October 17, 2022

External URL in React

https://bobbyhadz.com/blog/react-redirect-to-external-url

https://stackoverflow.com/questions/42914666/react-router-external-link

https://stackoverflow.com/questions/71333662/external-link-not-working-when-using-link-from-react-router-dom

https://stackoverflow.com/questions/66905176/how-to-redirect-to-external-url-onclick-in-react

https://stackoverflow.com/questions/47447441/cant-open-new-tab-in-react-adds-localhost3000-on-link

https://www.kindacode.com/article/ways-to-open-an-external-link-in-react/

https://stackoverflow.com/questions/18476373/how-to-add-target-blank-to-javascript-window-location

window.open - open link in a new window

window.location - open link in current window 

Import variables, functions from JavaScript files

https://bobbyhadz.com/blog/react-import-variable-from-another-file

https://stackoverflow.com/questions/38467574/import-javascript-file-and-call-functions-using-webpack-es6-reactjs

https://stackoverflow.com/questions/38467574/import-javascript-file-and-call-functions-using-webpack-es6-reactjs

ES6 JavaScript object destructuring

Extract array from nested object by destructuring:

{
"status": "success",
"time": "2022-10-17T17:09:50.486Z",
"result": 10,
"data": {
"posts": [ { "_id": "id", "image": "url", "link": "url",
"title": "title", "text": "text", "__v": 0, "counter": 1 } ]
}
}
const { data: { posts } = [] } = data; // extracting posts array from data

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

https://www.w3schools.com/react/react_es6_destructuring.asp

https://blog.bitsrc.io/getting-nested-value-by-using-javascript-7828f7768cc7

https://stackoverflow.com/questions/909003/getting-the-first-index-of-an-object

https://dmitripavlutin.com/javascript-object-destructuring/

https://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/

https://itnext.io/using-es6-to-destructure-nested-objects-in-javascript-avoid-undefined-errors-that-break-your-code-612ae67913e9

Sunday, October 16, 2022

Fetch data from local JSON file in React

How to access public files in React and fetch JSON data from local file:

http://localhost:3000/data.json // JSON located in /ReactProject/public/data.json

const { data, loading, error } = useFetch('data.json');

https://akhtarvahid.medium.com/how-to-access-fetch-the-local-json-file-to-react-5ce07c43731d

Saturday, October 15, 2022

Fetching JSON data from API with useEffect

import { useEffect, useState } from 'react';

export default function useFetch(url) {
const [data, setData] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
setLoading(true);
fetch(url, {
method: 'GET',
mode: 'cors',
dataType: 'json',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((res) => {
if (!res.ok) {
throw new Error(
`HTTP ${res.status} ${res.statusText}. Fetch ${res.url}`
);
}
return res.json();
})
.then((obj) => {
setData(obj);
console.log(`Fetched ${url}`);
})
.catch((err) => {
setError(err);
console.log(err); // throw new Error || err.message
})
.finally(() => {
setLoading(false);
});
}, [url]);

return { data, error, loading };
}

https://www.codementor.io/@mohammedelhossinyriaad/how-the-useeffect-react-hook-work-1cq3g0g8bd

https://www.smashingmagazine.com/2020/07/custom-react-hook-fetch-cache-data/

https://www.robinwieruch.de/react-hooks-fetch-data/

https://dev.to/shaedrizwan/building-custom-hooks-in-react-to-fetch-data-4ig6

https://www.developerway.com/posts/how-to-fetch-data-in-react

https://use-http.com/#/

Failed to execute 'removeChild' on 'Node'

Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

// Try to use firstChild etc when selecting element =>

document.querySelector('main').lastChild.innerHTML;

//

Tuesday, September 27, 2022

Fetching data from API

https://javascript.info/json

https://learn.javascript.ru/fetch

https://blog.logrocket.com/modern-api-data-fetching-methods-react/

https://stackoverflow.com/questions/39019094/reactjs-get-json-object-data-from-an-url

const fetchData = fetch('api/v1/cards', {
method: 'GET',
dataType: 'json',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((res) => res.json())
.then((obj) => {
// console.log(obj.data.cards);
// console.log(obj);
return Promise.resolve(obj.data.cards);
})
.catch((err) => {
console.log('Error getting data', err);
throw err;
});

console.log(fetchData);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

https://stackoverflow.com/questions/33237200/fetch-response-json-gives-responsedata-undefined

https://stackoverflow.com/questions/51619534/fetch-data-from-mongoose-and-put-into-an-array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

https://stackoverflow.com/questions/64611880/how-to-fetch-an-array-object-from-api-json-file

https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call

https://stackoverflow.com/questions/37533929/how-to-return-data-from-promise

https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data

https://stackoverflow.com/questions/60791658/value-undefined-returned-from-fetch-promise

https://stackoverflow.com/questions/12460378/how-to-get-json-from-url-in-javascript

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://stackoverflow.com/questions/66655216/why-is-my-response-data-undefined-when-sending-a-fetch

https://stackoverflow.com/questions/72217657/fetch-json-data-from-url-and-write-in-a-file

https://www.freecodecamp.org/news/json-stringify-example-how-to-parse-a-json-object-with-javascript/

https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data

Wednesday, September 21, 2022

Node server backend for React App

cat /etc/hosts

http://localhost:3001/ === http://127.0.0.1:3001/

run react and node servers in parallel on UNIX => & as separator in react-app/package.json

"scripts": {
"start": "react-scripts start & nodemon node src/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},

npm init -y // if install new empty project

npm i dotenv // in existing project

npm i express // in existing project

sudo npm i nodemon -g // automatically restarts node server after change

npm list -g // global install === -g

/usr/local/lib

├── eslint@8.22.0

├── live-server@1.2.2

├── node-sass@7.0.1

├── nodemon@2.0.20

└── npm-run-all@4.1.5

https://stackoverflow.com/questions/30950032/how-can-i-run-multiple-npm-scripts-in-parallel

https://towardsdev.com/how-to-set-up-a-node-js-express-server-for-react-c19104568d12

https://www.freecodecamp.org/news/how-to-create-a-react-app-with-a-node-backend-the-complete-guide/

https://www.geeksforgeeks.org/how-to-connect-node-js-with-react-js/

Tuesday, September 20, 2022

Understanding what are props in React

// search-box.jsx

import './search-box.scss';

const SearchBox = (props) => (
<input
className='search'
type='search'
placeholder={props.placeholder}
onChange={props.onSearchChange}
/>
);

export default SearchBox;

// is same as above but worse in terms of code

import './search-box.scss';

export const SearchBox = ({ placeholder, onSearchChange }) => (
<input
className='search'
type='search'
placeholder={placeholder}
onChange={onSearchChange}
/>
);

export default SearchBox;

// App.js

<SearchBox
placeholder='Search...'
onSearchChange={this.onSearchChange}
/>

//

`value` prop to a form field without an `onChange` handler

You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

<input value='' />

// change to defaultValue=''

Pass multiple parameters to onClick function

Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.

If parameter is function (clickHandler in this case), pass argument as function => clickHandler();

import Button from './btn';
import { useNavigate } from 'react-router-dom';

export default function BtnNav(footer, btnText, btnLink, clickHandler) {
const navigate = useNavigate();
return (
<ul className={`${footer}__nav`}>
{btnText.map((el, index) => (
<li key={`${footer}-k-${index}`}>
<Button
id={`${footer}-btn-${index}`}
className={`${footer}-btn-${index}`}
onClick={() => {
navigate(btnLink[index]);
clickHandler();
}}

content={el}
/>
</li>
))}
</ul>
);
}

// to avoid message error clickHandler, pass empty function as onClick in necessary components

const falseClick = () => {};

https://blog.openreplay.com/3-ways-of-passing-multiple-parameters-to-the-onclick-handler-in-react

https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs