TypeError: data.map is not a function in React-Redux using jsonPlaceholder perform CRUD operation

I have try many times to solve that error but don’t know every time why that error comes or in network tab delete api called but it’s undefined, so please help me to solve it!
Also I see all the other sites to solve this but it’s never solve.

[Screenshots here][1]
[1]: https://i.stack.imgur.com/8scr3.jpg
[2]: https://i.stack.imgur.com/V9lhH.jpg

  tablelistReducer.js

  import * as actionTypes from '../actions/actionTypes'
  const initialState = {
  loading: false,
  posts: [],
  error: false,

 }

const listReducer = (state = initialState, action) => {
 switch (action.type) {
    case actionTypes.FETCH_REQUEST:
        return {
            ...state,
            loading: true,
            error: false,
            posts: []

        }
    case actionTypes.FETCH_REQUEST_SUCCESS:
        return {
            ...state,
            loading: false,
            posts: action.payload,
            error: false
        }
    case actionTypes.FETCH_REQUEST_FAIL:
        return {
            ...state,
            loading: false,
            posts: [],
            error: action.payload
        }

  case actionTypes.DELETE_POST:
    
      // const deletedPost =  state.posts.filter(post => post !== action.payload)
        return  {
            ...state,
            posts: state.posts.filter(post => post !== action.payload)
        }

        
    default:
        return state

  }
}

 export default listReducer




listActions.js

import * as actionTypes from "./actionTypes";
import userService from "../services/userService";


 const fetchRequest = () => {
  return {
    type: actionTypes.FETCH_REQUEST
  }
 }

const fetchRequestSuccess = (posts) => {
 return {
      type: actionTypes.FETCH_REQUEST_SUCCESS,
    payload: posts
  }
 }

 const fetchRequestFail = (error) => {
   return {
    type: actionTypes.FETCH_REQUEST_FAIL,
    payload: error
   };
 };

  export function fetchUserList() {
  return (dispatch) => {
    dispatch(fetchRequest())
    return userService
        .getUsers()
        .then((res) => {
            dispatch(fetchRequestSuccess(res))
            console.log(res)
            return res
        })
        .catch((err) => {
            dispatch(fetchRequestFail(err))
            console.log(err)

        })
    }
  }

  export const deletePost = id => dispatch => {
  return userService.deleteUsers(id)
 // .then(res => res.json())
  
  .then(id=> {
    dispatch({
        type: actionTypes.DELETE_POST,
        payload: id
            })
  //  return response       
  })
.catch(error => {
    console.log(error);

  })
  }

userService.js

import api from "./apis/api";
import {hydrateUsers} from './transformers/userTransformer';

class UserService {
 getUsers() {
  return api.user.getUsers().then(hydrateUsers);
 };

 postUsers(){
  return api.user.postUsers().then(hydrateUsers);
 };

   deleteUsers(){
  return api.user.deleteUsers().then(hydrateUsers);

     }
 }

   export default new UserService();


 userApi.js

  import api from "./api";

   export default class UserAPI {
   getUsers() {
   return api.get("/users");

   };

  postUsers(data){
   return api.post("/users", data );
  };

  deleteUsers(id){
  return api.delete(`/users/${id}`);
  }

   }


  api.js

 import axios from "axios";
 import UserAPI from "./userApi";
 import storage from "../storage";
 import _ from "lodash";

 const BASEURL = "https://jsonplaceholder.typicode.com";

 class API {
 __user = new UserAPI();

api = axios.create({
 baseURL: BASEURL,
  transformRequest: [(data) => JSON.stringify(data)],
   headers: {
    Accept: "application/json",
  "Content-Type": "application/json",
   },
 });
  get user() {
  return this.__user;
 }

 get(url, ...args) {
 return this.sendRequestInternal(this.api.get, url, ...args);
 }

  post(url, ...args) {
   return this.sendRequestInternal(this.api.post, url, ...args);
  }

   patch(url, ...args) {
  return this.sendRequestInternal(this.api.patch, url, ...args);
 }

 delete(url, ...args){
return this.sendRequestInternal(this.api.delete, url, ...args);

  }

 sendRequestInternal(requestFunc, url, ...args) {
const token = storage.get("token");
if (token) {
  this.api.defaults.headers.common["Authorization"] = `Bearer ${token}`;
}
   return requestFunc(url, ...args)
    .then((response) => response.data && response.data)
    .catch((error) => {
      if (error.response) {
      if (_.get(error, ["response", "data", "status"], 500) === 401) {
        storage.clearAll();
        window.location = "/";
      }
    }
    throw error;
  });
   }
  }

  export default new API();


  TableList.js(main component)

   import React from 'react';
   import { connect } from 'react-redux';
   import { Table } from 'react-bootstrap';
   import { fetchUserList,  deletePost} from '../actions/listActions';
   import { get } from 'lodash';



   class TableList extends React.Component {

   componentDidMount() {
    this.props.loadTableList();
       }

      render() {
    const { tableList } = this.props;

    return (
        <>     
        <div style={{ margin: 110 }}>
        <Table striped bordered hover>
                <thead>
                    <tr>
                        <th>id</th>
                        <th>Name</th>
                        <th>Email</th>
            
                    </tr>
                </thead>
                <tbody>
                    {tableList.map(user => {
                            return <tr key={user.id}>
                               <td>{user.id}</td>
                              <td>{user.name}</td>
                              <td>{user.email}</td>
                                     <td>
                        <button onClick={()=>this.props.deletePosts(user.id)}>Delete</button>
                    </td>
                   </tr>             
                   } )}
        
                </tbody>
            </Table>
            

        </div>
      </>
     )}}


     const mapStateToProps = (state) => {
    return {
    tableList: get(state, ['listReducer', 'posts'], [])
   }
   }

   const mapDispatchToProps = (dispatch) => {
   return {
     loadTableList: () => dispatch(fetchUserList()),
    deletePosts : (id)=>dispatch(deletePost(id)),
   //addNewpost : ()=>dispatch(addPost())

    }
   }


    export default connect(mapStateToProps, mapDispatchToProps)(TableList)
  

fail to npm install canvas

github repository = https://github.com/VoiceSpaceUnder5/VoiceSpace

This is a project that I was working on until November of last year and I didn’t commit after that time. I cloned it today and tried to run it, but I got the following error message.

versions

error messages

npm ERR! code 1
npm ERR! path /Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build
npm ERR! Failed to execute '/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/bin/node /Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release/canvas.node --module_name=canvas --module_path=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v93' (1)
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using [email protected]
npm ERR! node-pre-gyp info using [email protected] | darwin | arm64
npm ERR! node-pre-gyp info check checked for "/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release/canvas.node" (not found)
npm ERR! node-pre-gyp http GET https://github.com/Automattic/node-canvas/releases/download/v2.9.0/canvas-v2.9.0-node-v93-darwin-unknown-arm64.tar.gz
npm ERR! node-pre-gyp ERR! install response status 404 Not Found on https://github.com/Automattic/node-canvas/releases/download/v2.9.0/canvas-v2.9.0-node-v93-darwin-unknown-arm64.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not installable for [email protected] and [email protected] (node-v93 ABI, unknown) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp WARN Hit error response status 404 Not Found on https://github.com/Automattic/node-canvas/releases/download/v2.9.0/canvas-v2.9.0-node-v93-darwin-unknown-arm64.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | darwin | arm64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | darwin | arm64
npm ERR! gyp info find Python using Python version 3.9.7 found at "/opt/homebrew/opt/[email protected]/bin/python3.9"
npm ERR! gyp info spawn /opt/homebrew/opt/[email protected]/bin/python3.9
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/hyeongtaekim/Library/Caches/node-gyp/16.13.1/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/hyeongtaekim/Library/Caches/node-gyp/16.13.1',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/hyeongtaekim/Library/Caches/node-gyp/16.13.1/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! /bin/sh: pkg-config: command not found
npm ERR! gyp: Call to 'pkg-config pixman-1 --libs' returned exit status 127 while in binding.gyp. while trying to load binding.gyp
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:259:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! gyp ERR! System Darwin 20.4.0
npm ERR! gyp ERR! command "/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/bin/node" "/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release/canvas.node" "--module_name=canvas" "--module_path=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v93"
npm ERR! gyp ERR! cwd /Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas
npm ERR! gyp ERR! node -v v16.13.1
npm ERR! gyp ERR! node-gyp -v v8.4.0
npm ERR! gyp ERR! not ok
npm ERR! node-pre-gyp ERR! build error
npm ERR! node-pre-gyp ERR! stack Error: Failed to execute '/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/bin/node /Users/hyeongtaekim/.nvm/versions/node/v16.13.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release/canvas.node --module_name=canvas --module_path=/Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas/build/Release --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v93' (1)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/Users/hyeongtaekim/VoiceSpace/front/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js:89:23)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! node-pre-gyp ERR! stack     at maybeClose (node:internal/child_process:1064:16)
npm ERR! node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
npm ERR! node-pre-gyp ERR! System Darwin 20.4.0
npm ERR! node-pre-gyp ERR! command "/Users/hyeongtaekim/.nvm/versions/node/v16.13.1/bin/node" "/Users/hyeongtaekim/VoiceSpace/front/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
npm ERR! node-pre-gyp ERR! cwd /Users/hyeongtaekim/VoiceSpace/front/node_modules/canvas
npm ERR! node-pre-gyp ERR! node -v v16.13.1
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v1.0.6
npm ERR! node-pre-gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/hyeongtaekim/.npm/_logs/2022-02-09T05_30_57_337Z-debug.log```

MUI persistent drawer nav bar breaks for a particular route

I’m new to the MUI library. I’ve managed to build a nav bar and it works fine for one route (Dashboard). But for the candidate route it collapses as shown : Screengrab of candidate route where the nav bar collapses

Screen grab of the dashboard route where the nav bar doesn’t break :
Screen grab of Dashboard route where nav bar renders as expected

Drawer code:

import { styled, useTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import MuiAppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import MenuIcon from "@mui/icons-material/Menu";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import MenuList from "@mui/material/MenuList";
import MenuItem from "@mui/material/MenuItem";
import PersonIcon from "@mui/icons-material/Person";
import DashboardIcon from "@mui/icons-material/Dashboard";
import LogoutIcon from "@mui/icons-material/Logout";

import { NavLink, withRouter, Switch, Route } from "react-router-dom";

import Routes from "./Routes";

const drawerWidth = 240;

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== "open",
})(({ theme, open }) => ({
  transition: theme.transitions.create(["margin", "width"], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  ...(open && {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: `${drawerWidth}px`,
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
  }),
}));

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
  justifyContent: "flex-end",
}));

const PersistentDrawerLeft = (props) => {
  const theme = useTheme();
  const [open, setOpen] = React.useState(true);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  const activeRoute = (routeName) => {
    return props.location.pathname === routeName ? true : false;
  };

  return (
    <Box sx={{ display: "flex" }}>
      <AppBar position="fixed" open={open}>
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={handleDrawerOpen}
            edge="start"
            sx={{ mr: 2, ...(open && { display: "none" }) }}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap component="div">
            Welcome!
          </Typography>
        </Toolbar>
      </AppBar>
      <Drawer
        sx={{
          width: drawerWidth,
          flexShrink: 0,
          "& .MuiDrawer-paper": {
            width: drawerWidth,
            boxSizing: "border-box",
          },
        }}
        variant="persistent"
        anchor="left"
        open={open}
      >
        <DrawerHeader>
          <img
            src={require("../images/icon.jpg")}
            alt="icon"
            style={{ height: "70px" }}
          />
          <IconButton onClick={handleDrawerClose}>
            {theme.direction === "ltr" ? (
              <ChevronLeftIcon />
            ) : (
              <ChevronRightIcon />
            )}
          </IconButton>
        </DrawerHeader>
        <Divider />
        <MenuList>
          {Routes.map((prop, key) => {
            return (
              <NavLink
                to={prop.path}
                style={{ textDecoration: "none", color: "gray" }}
                key={key}
              >
                <MenuItem selected={activeRoute(prop.path)}>
                  <ListItemIcon>
                    {prop.sidebarName === "Dashboard" ? (
                      <DashboardIcon />
                    ) : prop.sidebarName === "Candidate" ? (
                      <PersonIcon />
                    ) : (
                      <LogoutIcon />
                    )}
                  </ListItemIcon>
                  <ListItemText primary={prop.sidebarName} />
                </MenuItem>
              </NavLink>
            );
          })}
        </MenuList>
        <Divider />
      </Drawer>
      <Switch>
        {Routes.map((route) => (
          <Route exact path={route.path} key={route.path}>
            <route.component />
          </Route>
        ))}
      </Switch>
    </Box>
  );
}

export default withRouter(PersistentDrawerLeft);

Candidate form:

import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import FormControl from "@material-ui/core/FormControl";
import FormLabel from "@material-ui/core/FormLabel";
import RadioGroup from "@material-ui/core/RadioGroup";
import Radio from "@material-ui/core/Radio";
import Button from "@material-ui/core/Button";
import Box from "@mui/material/Box";

import BasicDatePicker from "./BasicDatePicker";
import BasicSelect from "./BasicSelect";

const defaultValues = {
  name: "",
  email: "",
  age: 0,
  gender: "",
  mobile: "",
  currentCompany: "",
  currentCtc: "",
  expectedCtc: "",
  status: "",
};
const NewCandidateForm = () => {
  const [formValues, setFormValues] = useState(defaultValues);
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormValues({
      ...formValues,
      [name]: value,
    });
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    
  };
  return (
    <Box
      component="form"
      sx={{
        "& .MuiTextField-root": { m: 1, width: "25ch" },
      }}
      
      
    >
      <form onSubmit={handleSubmit}>
        <Grid
          container
          direction="column"
          spacing={1} 
          
        >
          {/* Name field */}
          <Grid item>
            <TextField
              id="name-input"
              name="name"
              label="Name"
              type="text"
              value={formValues.name}
              onChange={handleInputChange}
            />
          </Grid>
          {/* Date of Birth */}
          <Grid item>
            <BasicDatePicker />
          </Grid>
          {/* Gender */}
          <Grid item>
            <FormControl>
              <FormLabel>Gender</FormLabel>
              <RadioGroup
                name="gender"
                value={formValues.gender}
                onChange={handleInputChange}
              >
                <FormControlLabel
                  key="male"
                  value="male"
                  control={<Radio size="small" />}
                  label="Male"
                />
                <FormControlLabel
                  key="female"
                  value="female"
                  control={<Radio size="small" />}
                  label="Female"
                />
                <FormControlLabel
                  key="other"
                  value="other"
                  control={<Radio size="small" />}
                  label="Other"
                />
              </RadioGroup>
            </FormControl>
          </Grid>
          {/* Email */}
          <Grid item>
            <TextField
              id="email-input"
              name="email"
              label="Email"
              type="email"
              value={formValues.email}
              onChange={handleInputChange}
            />
          </Grid>
          {/* Mobile */}
          <Grid item>
            <TextField
              id="mobile-input"
              name="mobile"
              label="Mobile"
              type="number"
              value={formValues.mobile}
              onChange={handleInputChange}
            />
          </Grid>
          {/* Status select */}
          <BasicSelect />
          {/* Current Company */}
          <Grid item>
            <TextField
              id="currentCompany-input"
              label="Current Company"
              name="currentCompany"
              type="text"
              value={formValues.currentCompany}
              onChange={handleInputChange}
            />
          </Grid>
          {/* Current CTC */}
          <Grid item>
            <TextField
              id="ctc-input"
              label="Current CTC"
              name="currentCtc"
              type="number"
              value={formValues.currentCtc}
              onChange={handleInputChange}
            />
          </Grid>
          {/* Expected CTC */}
          <Grid item>
            <TextField
              id="ectc-input"
              label="Expected CTC"
              name="expectedCtc"
              type="nuber"
              value={formValues.expectedCtc}
              onChange={handleInputChange}
            />
          </Grid>
          <Button
            className="SubmitFormButton"
            variant="contained"
            style={{ width: "250px", alignItems: "center", marginTop: "20px" }}
            type="submit"
          >
            Submit
          </Button>
        </Grid>
      </form>
    </Box>
  );
};
export default NewCandidateForm;

Rotue:

import React from "react";
import NewCandidateForm from "./NewCandidateForm";
import BarChart from "./BarChart";
import StackedChart from "./StackedChart";
import { styled } from "@mui/material/styles";

const roleData = {
  count: [2, 3, 4, 10, 4, 3, 3, 2],
  categories: [
    "AL2",
    "SAL1",
    "SAL2",
    "SDE1",
    "SDE2",
    "SDE3",
    "Specialist Mgr",
    "Sr. Specialist Mgr",
  ],
  titleText: "Role coverage",
  color: "#CB5757",
};

const spocData = {
  count: [2, 3, 4],
  categories: ["Data1", "Data2", "Data3"],
  titleText: "SPOC",
  color: "#CF9152",
};

const sourceData = {
  count: [2, 5, 1, 7, 5, 4, 8, 3, 4, 7, 2, 1, 5],
  categories: [
    "Data1",
    "Data2",
    "Data3",
    "Data4",
    "Data5",
    "Data6",
    "Data7",
    "Data8",
    "Data9",
    "Data10",
    "Data11",
    "Data12",
    "Data13",
  ],
  titleText: "Source",
  color: "#91CF52",
};

const panelData = {
  count: [3, 4, 6, 2, 4],
  categories: ["Data1", "Data2", "Data3", "Data4", "Data5"],
  titleText: "Panel Contribution",
  color: "#52CFCF",
};

const podData = {
  count: [3, 2, 3, 1],
  categories: ["2-3 yrs", "4-6 yrs", "6-8 yrs", "10+ yrs"],
  titleText: "POD Coverage",
  color: "#5291CF",
};

const companyData = {
  count: [2, 4, 5, 2, 1, 5],
  categories: [
    "Data1",
    "Data2",
    "Data3",
    "Data4",
    "Data5",
    "Data6",
  ],
  titleText: "Hired from",
  color: "#CF52CF",
};

const drawerWidth = 340;
const open = true;

const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
  ({ theme, open }) => ({
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: `-${drawerWidth}px`,
    ...(open && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen,
      }),
      marginLeft: 0,
    }),
  })
);

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
  justifyContent: "flex-end",
}));

const Home = () => {
  return (
    <Main open={open}>
      <DrawerHeader />
      <StackedChart />
      <br />
      <br />
      <div style={{ marginTop: "100px", display: "flex", flexDirection: "row", flexWrap: "wrap",rowGap: "250px", coulmnGap:"100px"}}>
        <BarChart data={roleData} style={{ padding: "200px" }} />
        <BarChart data={spocData} />
        <BarChart data={sourceData} />
        <BarChart data={panelData} />
        <BarChart data={podData} />
        <BarChart data={companyData} />
      </div>
    </Main>
  );
};

const CandidateForm = () => {
  return (
    <Main open={open}>
      <DrawerHeader />
      <NewCandidateForm />
     {/* <h1>Test</h1> */}
     
    </Main>
  );
};

const Logout = () => {
  return (
    <Main open={open}>
      <DrawerHeader />
      <h1>Logout</h1>
    </Main>
  );
};

const Routes = [
  {
    path: "/",
    sidebarName: "Dashboard",
    component: Home,
  },
  {
    path: "/candidate",
    sidebarName: "Candidate",
    component: CandidateForm,
  },
  {
    path: "/logout",
    sidebarName: "Logout",
    component: Logout,
  },
];

export default Routes;

When I tried to switch component in the above code with just the a h1 tag (that has been commented out), the nav bar works fine. Wonder if there’s a problem in the candidate form code that breaks the UI in the left pane.

Any help in debugging the issue will be much appreciated.

(NextJS/ReactJS) Delaying router pathName until after next-page-transitions is done

I have two separate things going on in a simple setup. I am using the following code:

className={router.pathname.startsWith("/pagename") ? "menu-active" : ""}

to assign the menu-active class to the pagename nav link when we’re on the pagename page.

And I am using

        <PageTransition timeout={450} classNames="page-transition">
      <Component {...pageProps} key={router.route} />
        </PageTransition>
        <style jsx global>{`
          .page-transition-enter {
            opacity: 0;
          }
          .page-transition-enter-active {
            opacity: 1;
            transition: opacity 450ms;
          }
          .page-transition-exit {
            opacity: 1;
          }
          .page-transition-exit-active {
            opacity: 0;
            transition: opacity 450ms;
          }
        `}</style>

pretty much verbatim from the next-page-transitions docs page, to have a 450ms fade to white between pages.

Here’s the problem. I use menu-active to change the font-style of the active page link to italics, and to change its color to orange. But when you change pages, it seems that the class is applied before the transition happens. In other words, you can see the menu change before the fade out to white even occurs.

I figured I could delay the transition by 450ms and then the change would happen right as the fade was finishing, and that works fine for the color change; but not for the font style. Since font style doesn’t work with transition-delay, I am trying to figure out some other way to delay the application of this class/style.

Perhaps I’m going about this all wrong though. Any recommendations?

vue buefy table sort nested array

I have a 2d array i’m displaying in a table using buefy, normally when I want to sort a column on render I can simply add default-sort=”field name” and it will sort for me. But because of the 2d nested array it doesn’t seem to work. Has anyone done this before? I’m trying to sort the table by the last column’s values.

<b-table
  :data="testArray"
  default-sort="quantity"
>
      <b-table-column label="Jan" v-slot="props">
        {{ props.row[1].quantity }}
      </b-table-column>
      .
      .
      .
      <b-table-column label="December" field="quantity" numeric v-slot="props">
        {{ props.row[11].quantity }}
      </b-table-column>
</b-table>

I have tried using just “quantity”, i have also tried using the whole “props.row[11].quantity” but that doesn’t also work.
The table itself renders just fine however,

enter image description here

My actual dataset goes like this:

[
    [{quantity=0},...,{quantity=0}],
    [{quantity=333},....,{quantity=717}],
    .
    .
    .
    [{quantity=0},...,{quantity=0}],
]

Its an array of arrays containing json objects, note the objects dont only contain quantity, they have other fields im omitting for clarity

Cycle through list using buttons/arrow images HTML and Jquery

Hi I am making a game server that uses html for menus. I have been struggling on how to do this for a few days. Basically I have a list that I want to be used kind of like a range slider but I want there to be buttons on the left and right of it that will scroll through the list only showing one item at a time. Here is a generic version on the code I would be using for the html.

<div class="input">
            <div class="label">Item1</div>
            <div class="value" data-legend="/1"></div>
            <div class="type-range">
              <a href="#" class="arrow arrow-left">&nbsp;</a>
              <input value="1" type="range" class="type1" min="0" max="1">
              <a href="#" class="arrow arrow-right">&nbsp;</a>
            </div>
          </div>

I want it to basically have arrow images on both sides and the list items in the middle like this…

<- Item1 ->

When you click to the left it gets the next ul value

<- Item2 ->

I know how to do the CSS and a lot of the other stuff but I am struggling with the scrolling through the UL list pretty much. Thanks.

Code stops working after applying Orbit Controls

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>THREE.JS</title>
    <link rel="stylesheet" href="index_styles.css" />
</head>
<body>
    

    <script src="./js/three.js"></script>
    <script src="./js/OrbitControls.js"></script>
    <script>
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 1000 );

        const renderer = new THREE.WebGLRenderer();
        // renderer.setPixelRatio(window.devicePixelRatio)
        renderer.setSize( window.innerWidth/2, window.innerHeight/2 );
        document.body.appendChild( renderer.domElement );

        const geometry = new THREE.BoxGeometry();
        const material = new THREE.MeshStandardMaterial( { color: 0x00ff00 } );
        const cube = new THREE.Mesh( geometry, material );
        scene.add( cube );

        const pointLight1 = new THREE.PointLight(0xffffff);
        pointLight1.position.set(5,0,10);
        const pointLight2 = new THREE.PointLight(0xffffff);
        pointLight2.position.set(-5,-5,10);
        const lightHelper = new THREE.PointLightHelper(pointLight1)

        const ambientLight = new THREE.AmbientLight(0xffffff);

        scene.add(pointLight1, pointLight2, lightHelper)

        renderer.render( scene, camera );

        const controls = new THREE.OrbitControls( camera, renderer.domElement );
        camera.position.setZ(10);
        controls.update();

        let increasing = true;

        function animate() {
            requestAnimationFrame( animate );

            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;

            if (cube.position.x <= 20 && increasing) {
                cube.position.x += 0.1
                increasing = true;
            } else if (cube.position.x > 20 || !(increasing)) {
                cube.position.x -= 0.1
                increasing = false;
                if (cube.position.x <= 0) {
                    increasing = true;
                }
            }

            controls.update();

            renderer.render( scene, camera );
        };

        animate();
    </script>
    
</body>
</html>

Everything in the code works if I do not include the line for OrbitControls. What am I doing wrong because as soon as I create the controls variable, the display is all black and the green cube disappears? I have included before and after pictures of what the display looks like with and without the code for orbit controls. Before:1 After:2

recoverTypedSignature function on @metamask/eth-sig-util is not working

It seems that every that the updated recoverTypedSignature function on @metamask/eth-sig-util is not working properly. As soon as I add it into the project, it gives out an error.

Any help would be greatly appreciated it.

The error is:

bundle.js:6306 Uncaught ReferenceError: Buffer is not defined at Object../node_modules/@metamask/eth-sig-util/node_modules/ethereumjs-util/dist/secp256k1v3-lib/der.js (bundle.js:6306:40) at Object.options.factory (bundle.js:84170:31) at webpack_require (bundle.js:83608:33) at fn (bundle.js:83841:21) at Object../node_modules/@metamask/eth-sig-util/node_modules/ethereumjs-util/dist/secp256k1v3-adapter.js (bundle.js:5932:11) at Object.options.factory (bundle.js:84170:31) at webpack_require (bundle.js:83608:33) at fn (bundle.js:83841:21) at Object../node_modules/@metamask/eth-sig-util/node_modules/ethereumjs-util/dist/index.js (bundle.js:5724:17) at Object.options.factory (bundle.js:84170:31)

The code is:


import { SignTypedDataVersion, recoverTypedSignature } from '@metamask/eth-sig-util';


const Request_Signature = (props: any) => {
    // Step 2:  Once user has authorized the use of its crypto wallet a signature can
    //          be requested

    async function sign_TypedDataV4() {
        const msgParamsOg = {
            domain: {
                // Defining the chain: 1 - Ethereum Main Net
                chainId: 1,
                // Friendly name
                name: "Initial Example Contract",
                // Additional way of verifying contract to make sure you are establishing contracts with the proper entity
                verifyingContract: "this",
                // Just let's you know the latest version. Definitely make sure the field name is correct.
                version: "1",
            },

            // Defining the message signing data content.
            message: {
                Request: "Please complete your authentication by signing this",
                username: "test_user",
            },
            // Refers to the keys of the *types* object below.
            primaryType: "LogIn",
            types: {
                EIP712Domain: [
                    {
                        name: "name",
                        type: "string",
                    },
                    {
                        name: "version",
                        type: "string",
                    },
                    {
                        name: "chainId",
                        type: "uint256",
                    },
                    {
                        name: "verifyingContract",
                        type: "address",
                    },
                ],
                // Refer to PrimaryType
                LogIn: [
                    {
                        name: "username",
                        type: "string",
                    },
                ],
            },
        };
        let msgParams = JSON.stringify(msgParamsOg);

        let account = props.account;
        var params = [account, msgParams];
        var method = "eth_signTypedData_v4";
        console.log('User Address:' + account);

        (window as any).ethereum.sendAsync(
            {
                method,
                params,
                account,
            },
            async function (err: Error, result: any) {
                if (err) return console.dir(err);
                if (result.error) {
                    alert(result.error.message);
                    return console.error("ERROR", result);
                }
                //console.log('TYPED SIGNED:' + JSON.stringify(result.result));

                let signature = result.result;

                const restored = recoverTypedSignature({
                    data: msgParamsOg as any,
                    signature,
                    version: SignTypedDataVersion.V4,
                  });

                console.log(restored);

            }
        );
    }


    return (
        <div>
            <button
                className='btn_main'
                type="button"
                onClick={async (e) => {
                    e.preventDefault();
                    sign_TypedDataV4();
                }}
            >
                Sign Now
            </button>
        </div>
    )
};

export default Request_Signature;

Add CSS if font does not load

With document.fonts.ready.then, it is possible to change CSS if a font is loaded.

Example:

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
});
@font-face {
  src: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/133207/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Lorem ipusm</div>

Now my question is:
Does something like document.fonts.NOT.ready.then exist? Or how can I change the CSS if the font gets not loaded?

Would be very thankful for help.

d3 5+ – Appending circles about a semi-circle or arc

Suppose we wanted to make a list-like visual. Setting the y logic for the circles can be as simple as:

var data = [0,1,2,3,4,5,6,7,8,9];

var yScale = d3.scaleLinear()
    .range([height,0])
    .domain([0,9]);

svg.selectAll(null)
    .data()
    .enter()
    .append('circle')
    .attr('y', function(d) { return yScale(d) })
    .attr('x', 100)
    .attr('r', 10)
    .style('fill', "#a6a6a6");

However, suppose we wanted to go for some style points and arrange the circles not in a blocky / tabular arrangement but rather arrange them about a circle or arc. I had this result in mind (only concerned with the outer circles):

enter image description here

While I think d3 does have trigonometric functions, I have never seen them used in pixel coordinates. I’d imagine the pseudo-code to be something like:

var semiCircleScale = d3.?????
    .range([250 degrees, 110 degrees])
    .domain([0,9]);

svg.selectAll(null)
    .data()
    .enter()
    .append('circle')
    .attr('y', function(d) { return semiCircleScale(d) })
    .attr('x', 100)
    .attr('r', 10)
    .style('fill', "#a6a6a6");

Question

Is anyone familiar with using circle / arc scales for use with x,y logic for appending shapes? Or is there an easier/less-math-intensive way?

app.post() returns index of C:/ instead of text

I am new to web development(creating my first local server) and I can’t understand what I am doing wrong.

Following is my code on HTML:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calculator</title>
  </head>
  <body>
  <form  action= "/" method="post">
  <input type="text" name="num1" placeholder="First Number">
  <input type="text" name="num2" value="" placeholder="Second number">
  <button type="submit" name="submit">Calculate</button>
  </form>

  </body>
</html>

and JS :

var express = require("express");
var app = express();

app.get("/", function(req, res)
{
  res.sendFile(__dirname + "/index.html");
})

 app.post("/index.html", function(req,res){
     res.send("Thanks for posting that!");
 });
app.listen(3000, () => {
  console.log("Server is running on port 3000")
});

But the Output I am getting when I press (calculate button) is the (index of C:/) i.e the directory of C and all the files in it …

image of output i am getting after i press calculate

What I am using:

noje.js, html5 , nodemon , hyper terminal , atom text editor

What I want to achieve:

A server that sends a request to display an html form that accepts 2 numbers and then displays the sum as a text message when some1 presses the calculate(submit) button.

What I have tried:

  1. form action= “/index.html” method=”post”

Well, like u guessed, just refreshes the form

  1. app.post(“/”, function(req,res)

Same Output(index of C)

Sorry For asking noob questions .. but can you please explain to me what I am doing wrong and point me in the right direction.

How i can loop a event with puppeteer

i have a little problem with puppeteer, i don’t know how to loop my event when the page refreshing. It work 1 time after i need to restart Chromium.

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false});

const rapidGiveway = await browser.newPage();
rapidGiveway.once('load', async () => {
console.log("Page loaded!")
const participate = await rapidGiveway.$x("//button[@id='giveaway-enter']");
await rapidGiveway.waitForXPath("//button[@id='giveaway-enter']", {visible: true})
await participate[0].click();
});
})();

Want to create a GIf that performs an HTTP request

Is it possible to embed js code (or any other code) in a GIF or any other type of image? For example I want to:

  1. create an animated image that moves (for example a GIF).
  2. every 5 minutes perform an http request
  3. if the results of the http request is true then change the GIF

for example a gif that changes from the sun to the moon depending on the time of day?

I am open to any technology or image type or tools. your help is appreciated

thanks

Define a function, lettersAfter, that accepts three arguments:

Hello I am learning how to code inside of JavaScript and I am taking an assessment but I am getting stumped on one of the questions. Could someone help me with this?

Define a function, lettersAfter, that accepts three arguments:
A string: The string to be searched
A string: A character to search for.
A number: The number of letters after the character to return
lettersAfter should return the letters following the first found occurrence of the search character. The letters returned should be limited to the number of the third argument.
Maybe it is to late in the day but my brain cannot solve this.

How to test azure timer function? javascript

I have a task that involves auto run by schedules. So I dived in to azure timer function, and tried creating sample timer function via vscode azure (see code below).

Question is, do you how to test it, in which we can at least display the context.log? thanks.


So here’s the structure that was generated.

enter image description here

Here’s the function.json

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    }
  ],
  "scriptFile": "../dist/TimerTrigger1/index.js"
}

And here’s index.ts

import { AzureFunction, Context } from '@azure/functions'

const timerTrigger: AzureFunction = async function (
  context: Context,
  myTimer: any
): Promise<void> {
  var timeStamp = new Date().toISOString()

  if (myTimer.isPastDue) {
    context.log('Timer function is running late!')
  }
  context.log('Timer trigger function ran!', timeStamp)
}

export default timerTrigger