I am trying to run my react app but process is not defined is coming up all the time. I am trying to connect with my smart contract using web3.js. My app.jsx file is,
import { useEffect, useState } from "react";
import Web3 from "web3";
import detectEthereumProvider from "#metamask/detect-provider";
import { loadContract } from "./utils/load-contract";
// m,dKK#;fl99
const App = () => {
const [web3Api, setWeb3Api] = useState({
provider: null,
web3: null,
contract: null,
});
const [account, setAccount] = useState(null);
useEffect(() => {
const loadProvider = async () => {
// console.log(window.web3);
// console.log(window.ethereum);
// let provider = null;
// if (window.ethereum) {
// provider = window.ethereum;
// } else if (window.web3) {
// provider = window.web3.currentProvider;
// } else if (!process.env.production) {
// provider = new Web3("http://127.0.0.1:7545");
// }
// try {
// await provider.enable();
// } catch (error) {
// console.log("error", error);
// }
const provider = await detectEthereumProvider();
const contract = await loadContract("Founder", provider);
console.log(contract);
// console.log(provider);
// console.log(prov)
if (provider) {
console.log("Ethereum successfully detected!");
provider.request({ method: "eth_requestAccounts" });
setWeb3Api({
web3: new Web3(provider),
provider,
contract,
});
} else {
console.error("Please install MetaMask!", error);
}
};
loadProvider();
}, []);
useEffect(() => {
const getAccount = async () => {
const acc = await web3Api.web3.eth.getAccounts();
setAccount(acc);
};
web3Api.web3 && getAccount();
}, [web3Api.web3]);
// console.log(web3Api.web3);
// console.log(account);
return (
<>
<div className="card text-center">
<div className="card-header">Funding</div>
<div className="card-body">
<h5 className="card-title">Balance: 20 ETH </h5>
<p className="card-text">
Account : {account ? account : "Not connected"}
</p>
{/*<button
type="button"
className="btn btn-success"
//connect to matamask
onClick={async () => {
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
console.log(accounts);
}}
> */}
{/* <button className="btn btn-success">Connect to metamask</button> */}
<button type="button" className="btn btn-success">
Transfer
</button>
<button type="button" className="btn btn-primary">
Withdraw
</button>
</div>
<div className="card-footer text-muted">Code Eater</div>
</div>
</>
);
};
export default App;
My load-contract file is,
import contract from "#truffle/contract";
export const loadContract = async (name, provider) => {
const res = await fetch(`/contracts/${name}.json`);
const Artifact = await res.json();
const _contract = contract(Artifact);
_contract.setProvider(provider);
const deployedContract = await _contract.deployed();
return deployedContract;
};
Now every time I run this app this error is kept coming,
Uncaught ReferenceError: process is not defined
at node_modules/util/util.js (util.js:109:1)
at __require2 (chunk-S5KM4IGW.js?v=0672b092:18:50)
at node_modules/#truffle/contract-schema/index.js (index.js:3:12)
at __require2 (chunk-S5KM4IGW.js?v=0672b092:18:50)
at node_modules/#truffle/contract/index.js (index.js:1:16)
at __require2 (chunk-S5KM4IGW.js?v=0672b092:18:50)
at index.js:15:18
Now why process is not defined is showing? What did i do wrong?
Now how to fix that. I am using node version 18.12.1 And i don't know how to solve this error. I can't find any good solution for this.
Related
I've tried everything, I used the standard input, without success, I already changed the onSubmit to onClick, without success, I already put the function in the onClick button without success, it only works when I remove the input field of type file
I am using Electron React Boilerplate
https://github.com/electron-react-boilerplate/electron-react-boilerplate
import { Button, Pane, FileUploader, FileCard, Alert } from 'evergreen-ui';
import VideoSnapshot from 'video-snapshot';
import Input from 'renderer/components/Input';
import React from 'react';
import axios from 'axios';
import ContainerMenu from '../components/ContainerMenu';
const Admin = () => {
const [name, setName] = React.useState('');
const [genre, setGenre] = React.useState('');
const [path, setPath] = React.useState('');
const [preview, setPreview] = React.useState(null);
const [submitError, setSubmitError] = React.useState('');
const [progress, setProgress] = React.useState(0);
const [files, setFiles] = React.useState([]);
const [fileRejections, setFileRejections] = React.useState([]);
const handleChange = React.useCallback((files) => setFiles([files[0]]), []);
const handleRejected = React.useCallback(
(fileRejections) => setFileRejections([fileRejections[0]]),
[]
);
const handleRemove = React.useCallback(() => {
setFiles([]);
setFileRejections([]);
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
setSubmitError('');
if (files.length === 0) {
setSubmitError('O arquivo não pode ser vazio');
return;
}
try {
const snapshoter = new VideoSnapshot(files[0]);
const previewSrc = await snapshoter.takeSnapshot();
if (previewSrc) setPreview(previewSrc);
} catch (error) {
console.log(error);
}
try {
// const previewData = new FormData();
// const previewObject = {
// preview: previewSrc,
// };
// previewData.append('file', previewObject);
// await axios.post('http://localhost:3000/api/upload', previewData);
const formData = new FormData();
formData.append('file', files[0]);
formData.append('name', name);
formData.append('genre', genre);
formData.append('path', 'videos');
const response = await axios.post(
'http://localhost:3000/api/upload',
formData,
{
onUploadProgress: (progressEvent) => {
const progress = (progressEvent.loaded / progressEvent.total) * 50;
setProgress(progress);
},
}
);
} catch (error) {
console.log(error);
setSubmitError(error.message);
}
};
return (
<div>
<ContainerMenu />
<div className="container">
<form
encType="multpart/form-data"
className="form-group"
onSubmit={handleSubmit}
>
<h2>Enviar Arquivos</h2>
<br />
<div>
<Input
type="text"
label="Nome"
placeholder="Nome ..."
onChange={setName}
value={name}
/>
</div>
<div>
<Input
type="text"
label="Gênero"
placeholder="Gênero ..."
onChange={setGenre}
value={genre}
/>
</div>
<div>
<Pane>
<FileUploader
label="Upload File"
description="You can upload 1 file. File can be up to 50 MB."
maxSizeInBytes={50 * 1024 ** 2}
maxFiles={1}
onChange={handleChange}
onRejected={handleRejected}
renderFile={(file) => {
const { name, size, type } = file;
const fileRejection = fileRejections.find(
(fileRejection) => fileRejection.file === file
);
const { message } = fileRejection || {};
return (
<FileCard
key={name}
isInvalid={fileRejection != null}
name={name}
onRemove={handleRemove}
sizeInBytes={size}
type={type}
validationMessage={message}
/>
);
}}
values={files}
/>
</Pane>
</div>
<div>
<Button
isLoading={progress > 0 && progress < 100}
marginRight={16}
appearance="primary"
type="submit"
>
Enviar {progress.toFixed(2)}%
</Button>
</div>
<br />
<div>{preview && <img src={preview} alt="preview" />}</div>
<br />
<div>
{submitError.length > 0 && (
<Alert intent="danger" title="Error">
{submitError}
</Alert>
)}
</div>
</form>
</div>
</div>
);
};
export default function App() {
return <Admin />;
}
I'm trying to display an error message when a user tries to sign in with an unregistered user but I'm not able to get that error message on the frontend(reactjs) that I am sending from my backend(nodejs, express, MongoDB).
I am using redux to handle the state of the react app.
user login form onSubmit code:
const onSubmit = (data) => {
if (isLogin) {
dispatch(signin(data, history));
} else {
dispatch(signup(data, history));
}
};
actions creators for auth
import * as api from "../api";
export const signin = (formData, history) => async (dispatch) => {
try {
// login the user
const { data } = await api.signIn(formData);
dispatch({ type: "AUTH", data });
history.push("/");
} catch (error) {
console.log(error);
dispatch({ type: "ERROR", data: error.response.data.message });
}
};
export const signup = (formData, history) => async (dispatch) => {
try {
// sign up the user
const { data } = await api.signUp(formData);
dispatch({ type: "AUTH", data });
history.push("/");
} catch (error) {
console.log(error);
}
};
reducers for auth:
const authReducer = (state = { authData: null }, action) => {
switch (action.type) {
case "AUTH":
localStorage.setItem("profile", JSON.stringify({ ...action?.data }));
return { state, authData: action?.data };
case "LOGOUT":
localStorage.clear();
return { state, authData: null };
case "ERROR":
return { state, authData: action?.data };
default:
return state;
}
};
export default authReducer;
Backend sign in code
const signin = async (req, res) => {
const { email, password } = req.body;
try {
const existingUser = await User.findOne({ email });
if (!existingUser)
return res.status(404).json({ message: "User doesn't exist." });
const isPasswordCorrect = await bcrypt.compare(
password,
existingUser.password
);
if (!isPasswordCorrect)
res.status(404).json({ message: "Invalid Credentials" });
const token = jwt.sign(
{ email: existingUser.email, id: existingUser._id },
"test",
{ expiresIn: "1h" }
);
res.status(200).json({ result: existingUser, token });
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
}
};
sign API
import axios from "axios";
const API = axios.create({
baseURL: process.env.REACT_APP_BASE_URL,
});
export const signIn = (formData) => API.post("/user/signin", formData);
export const signUp = (formData) => API.post("/user/signup", formData);
Anyone, please help me with this.
Screenshots of the error response in Postman:
I just debugged the issue. First install redux-devtools-extension by npm install --save redux-devtools-extension
Then apply this in store(index.js file in your case) as follows
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import App from "./App";
import { reducers } from "./reducers";
import { composeWithDevTools } from "redux-devtools-extension";
const middleware = [thunk];
const store = createStore(
reducers,
composeWithDevTools(applyMiddleware(...middleware))
);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
And now you can use the error message anywhere as follows (your Auth.js file)
import React, { useState } from "react";
import { useSelector } from "react-redux";
import Input from "../utils/Input";
import Label from "../utils/Label";
import { useForm, FormProvider } from "react-hook-form";
import { GoogleLogin } from "react-google-login";
import { useDispatch } from "react-redux";
import { useHistory } from "react-router";
import { signin, signup } from "../../actions/auth";
const Auth = () => {
const [isLogin, setIsLogin] = useState(true);
const formMethods = useForm();
const auth = useSelector((state) => state.auth);
const { authData } = auth;
const { handleSubmit } = formMethods;
console.log(authData);
const dispatch = useDispatch();
const history = useHistory();
const changeScreen = () => {
setIsLogin(false);
dispatch({ type: "LOGOUT" });
};
const onSubmit = (data) => {
if (isLogin) {
dispatch(signin(data, history));
} else {
dispatch(signup(data, history));
}
};
const googleSuccess = async (res) => {
const result = res?.profileObj;
const token = res?.tokenId;
try {
dispatch({ type: "AUTH", data: { result, token } });
history.push("/");
} catch (error) {
console.log(error);
}
};
const googleFailure = (error) => {
console.log(error);
console.log("Google sign in was unsuccessful");
};
return (
<section className="col-start-1 col-end-2 md:col-start-2 md:col-end-3 row-start-2 row-end-3 md:row-start-1 md:row-end-2 mx-3 sm:mx-0 md:my-auto">
<div className=" w-full max-w-md bg-primaryOne px-6 py-8 rounded-md shadow-md mx-auto">
<FormProvider {...formMethods}>
<form className="" onSubmit={handleSubmit(onSubmit)}>
<div className="w-full flex justify-around mb-2">
<button
className={`${
isLogin
? "bg-secondaryTwo"
: "transition bg-transparent hover:bg-secondaryTwo"
} text-white text-xs font-bold px-6 py-4 rounded-full`}
type="button"
onClick={() => setIsLogin(true)}
>
LOG IN
</button>
<button
className={`${
!isLogin
? "bg-secondaryTwo"
: "transition bg-transparent hover:bg-secondaryTwo"
} text-white text-xs font-bold px-6 py-4 rounded-full`}
type="button"
onClick={() => changeScreen()}
>
SIGN UP
</button>
</div>
<div>
{!isLogin && (
<div>
<Label labelName="Name" />
<Input inputName="name" type="text" bgColor="primaryTwo" />
</div>
)}
<div>
<Label labelName="Email" />
<Input inputName="email" type="email" bgColor="primaryTwo" />
</div>
<div>
<Label labelName="Password" />
<Input
inputName="password"
type="password"
bgColor="primaryTwo"
/>
</div>
</div>
<div className="text-center">
<button
type="button"
onClick={() => setIsLogin(!isLogin)}
className="text-neutral font-extralight text-xs pt-6"
>
{authData && <h1 style={{ color: "red" }}>{authData}</h1>}
{!isLogin
? "Already have an account? Log In"
: "Don't have an account? Sign Up"}
</button>
</div>
<button className="bg-secondaryTwo hover:bg-secondaryOne transition px-4 py-3 w-full rounded-md text-white font-bold mt-4 shadow-md">
{isLogin ? "Log In" : "Sign Up"}
</button>
<div className="flex items-center py-6">
<div className="w-1/2 h-px bg-white bg-opacity-40"></div>
<p className="text-white px-1 text-xs">OR</p>
<div className="w-1/2 h-px bg-white bg-opacity-40"></div>
</div>
<div>
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
onSuccess={googleSuccess}
onFailure={googleFailure}
cookiePolicy="single_host_origin"
render={(renderProps) => (
<button
className="bg-blue-600 hover:bg-blue-500 transition px-4 py-3 w-full rounded-md text-white font-bold mb-4 shadow-md"
type="button"
onClick={renderProps.onClick}
disabled={renderProps.disabled}
>
<i className="fab fa-google mr-2"></i>Continue with Google
</button>
)}
/>
</div>
</form>
</FormProvider>
</div>
</section>
);
};
export default Auth;
And one last thing. Check nested object before using its properties like error.response.data.message (your auth.js actions file)
import * as api from "../api";
export const signin = (formData, history) => async (dispatch) => {
try {
// login the user
const { data } = await api.signIn(formData);
dispatch({ type: "AUTH", data });
history.push("/");
} catch (error) {
console.log("An error occured while ");
const errMsg =
error.response && error.response.data.message
? error.response.data.message
: error.message;
dispatch({ type: "ERROR", data: errMsg });
console.log(errMsg);
}
};
export const signup = (formData, history) => async (dispatch) => {
try {
// sign up the user
const { data } = await api.signUp(formData);
dispatch({ type: "AUTH", data });
history.push("/");
} catch (error) {
console.log(error);
}
};
Hope it helps!
As far as I understood, everything is working fine, and actually, there is no error happening on the frontend side. You have to check the status code of "await api.signIn(formData);" response. If it is 200, it means that everything is ok otherwise you have to check the message in the response to get the message error. As on the frontend there is thrown error to be catched.
you can aslo use react-toastify . you can get status code and response message from error and store it in state object in reducers/auth.js and access it using useSelector() then create if else conditions according to status code and pass message to toast(#error_message#).
just see react-toastify and know how to use it.
i'm currently creating my first MERN App, and everything is going well, until something happened, and i'm going my try to explain because i need help !
What i'm doing is a facebook clone, where you can post something, you can delete your post and you can update your post, the logic is simple, i call dispatch to pass the data to the actions, the actions pass the data to the backend, and the backend return something to me and it saves in my store, because i'm using redux
The problem is that, when i have 2 post, and i want to delete a post, or maybe i want to edit it, the other post dissapears, it's like it loses its id and then loses the information, then i can't do anything but reaload the page, and it happens always
this is how it looks like, everything fine
Then, after trying to edit a post, the second one lost its information, and in the console, it says that Warning: Each child in a list should have a unique "key" prop, and i already gave each post the key={_id}, but the post lost it and i don't know how
Here's the code
Posts.js
import React, { useState } from "react";
import "./Posts.css";
import moment from "moment";
// Icons
import { BiDotsVertical, BiLike } from "react-icons/bi";
import { MdDeleteSweep } from "react-icons/md";
import { AiFillLike } from "react-icons/ai";
import { GrClose } from "react-icons/gr";
// Calling actions
import { deletePost, } from "../actions/posts.js";
// Gettin The Data From Redux
import { useSelector, useDispatch } from "react-redux";
const Posts = ({ setCurrentId }) => {
const [animation, setAnimation] = useState(false);
const [modal, setModal] = useState(false);
const [modalPost, setModalPost] = useState({});
// Getting The Posts
const posts = useSelector(state => state.posts);
const dispatch = useDispatch();
// Showing And Hiding Modal Window
const ModalWindow = post => {
setModalPost(post);
setModal(true);
};
// Liking the post
// const Like = id => {
// dispatch(giveLike(id));
// setAnimation(!animation);
// };
if (!posts.length) {
return <div>Loading</div>;
} else {
return (
<div className="Posts">
{/* // Modal window for better look to the post */}
{/* {modal && (
<div className="modalWindow">
<div className="container">
<div className="container-image">
<img src={modalPost.image} alt="" />
</div>
<div className="information">
<div className="container-information">
<div className="data-header">
<h2>
User <br />{" "}
<span style={{ fontWeight: "400" }}>
{moment(modalPost.createdAt).fromNow()}
</span>
</h2>
<span className="data-icon" onClick={() => setModal(false)}>
<GrClose />
</span>
</div>
<div className="message">
<h2>{modalPost.title}</h2>
<p>{modalPost.message}</p>
</div>
</div>
</div>
</div>
</div>
)} */}
{/* */}
{posts.map(post => {
const { _id, title, message, image, createdAt, likes } = post;
return (
<div className="Posts-container" key={_id}>
<div className="Fit">
<div className="Fit-stuff">
<h2 className="Fit-stuff_title">
User <br />{" "}
<span style={{ fontWeight: "400" }}>
{moment(createdAt).fromNow()}
</span>
</h2>
<a
className="Fit-stuff_edit"
href="#form"
onClick={() => setCurrentId(_id)}
>
<BiDotsVertical />
</a>
</div>
<div className="Fit-data">
<h2 className="Fit-data_title">{title}</h2>
<p className="Fit-data_message">{message}</p>
{image ? (
<div className="Fit-img">
<img
onClick={() => ModalWindow(post)}
src={image}
alt=""
/>
</div>
) : (
<div></div>
)}
</div>
<div className="Fit-shit">
<span>
{animation ? (
<AiFillLike className="fullLightBlue" />
) : (
<BiLike />
)}
{likes}
</span>
<span onClick={() => dispatch(deletePost(_id))}>
<MdDeleteSweep />
</span>
</div>
</div>
</div>
);
})}
</div>
);
}
};
export default Posts;
The form where i call update and create Post
import React, { useState, useEffect } from "react";
import Filebase from "react-file-base64";
// For the actions
import { useDispatch, useSelector } from "react-redux";
import { createPost, updatePost } from "../actions/posts.js";
import {
Wrapper,
FormContainer,
Data,
DataInput,
SecondDataInput,
FormContainerImg,
FormContainerButtons,
Buttons
} from "./FormStyled.js";
const Form = ({ currentId, setCurrentId }) => {
const [formData, setFormData] = useState({
title: "",
message: "",
image: ""
});
const specificPost = useSelector(state =>
currentId ? state.posts.find(p => p._id === currentId) : null
);
// Sending The Data And Editing The data
const dispatch = useDispatch();
useEffect(() => {
if (specificPost) setFormData(specificPost);
}, [specificPost]);
// Clear Inputs
const clear = () => {
setCurrentId(0);
setFormData({ title: "", message: "", image: "" });
};
const handleSubmit = async e => {
e.preventDefault();
if (currentId === 0) {
dispatch(createPost(formData));
clear();
} else {
dispatch(updatePost(currentId, formData));
clear();
}
};
return (
<Wrapper>
<FormContainer onSubmit={handleSubmit}>
<Data>
<DataInput
name="title"
maxLength="50"
placeholder="Title"
type="text"
value={formData.title}
onChange={e => setFormData({ ...formData, title: e.target.value })}
/>
<SecondDataInput
name="message"
placeholder="Message"
maxLength="300"
value={formData.message}
required
onChange={e =>
setFormData({ ...formData, message: e.target.value })
}
/>
<FormContainerImg>
<Filebase
required
type="file"
multiple={false}
onDone={({ base64 }) =>
setFormData({ ...formData, image: base64 })
}
/>
</FormContainerImg>
<FormContainerButtons>
<Buttons type="submit" create>
{specificPost ? "Edit" : "Create"}
</Buttons>
<Buttons onClick={clear} clear>
Clear
</Buttons>
</FormContainerButtons>
</Data>
</FormContainer>
</Wrapper>
);
};
export default Form;
My actions
import {
GETPOSTS,
CREATEPOST,
DELETEPOST,
UPDATEPOST,
LIKEPOST
} from "../actionTypes/posts.js";
import * as api from "../api/posts.js";
export const getPosts = () => async dispatch => {
try {
const { data } = await api.getPosts();
dispatch({ type: GETPOSTS, payload: data });
} catch (error) {
console.log(error);
}
};
export const createPost = newPost => async dispatch => {
try {
const { data } = await api.createPost(newPost);
dispatch({ type: CREATEPOST, payload: data });
} catch (error) {
console.log(error);
}
};
export const updatePost = (id, updatePost) => async dispatch => {
try {
const { data } = await api.updatePost(id, updatePost);
dispatch({ type: UPDATEPOST, payload: data });
} catch (error) {
console.log(error);
}
};
export const deletePost = id => async dispatch => {
try {
await api.deletePost(id);
dispatch({ type: DELETEPOST, payload: id });
} catch (error) {
console.log(error);
}
};
Redux Part
import {
GETPOSTS,
CREATEPOST,
DELETEPOST,
UPDATEPOST,
LIKEPOST
} from "../actionTypes/posts.js";
const postData = (posts = [], action) => {
switch (action.type) {
case GETPOSTS:
return action.payload;
case CREATEPOST:
return [...posts, action.payload];
case UPDATEPOST:
return posts.map(post =>
action.payload._id === post._id ? action.payload : posts
);
case DELETEPOST:
return posts.filter(post => post._id !== action.payload);
default:
return posts;
}
};
export default postData;
My controllers in the backend
import mongoose from "mongoose";
import infoPost from "../models/posts.js";
// Getting All The Posts
export const getPosts = async (req, res) => {
try {
const Posts = await infoPost.find();
res.status(200).json(Posts);
} catch (error) {
res.status(404).json({ message: error.message });
console.log(error);
}
};
// Creating A Post
export const createPost = async (req, res) => {
const { title, message, image } = req.body;
const newPost = new infoPost({ title, message, image });
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
console.log(error);
}
};
// Update A Post
export const updatePost = async (req, res) => {
const { id } = req.params;
const { title, message, image } = req.body;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No Post With Id Of ${id}`);
const updatedPost = { title, message, image, _id: id };
await infoPost.findByIdAndUpdate(id, updatedPost, { new: true });
res.json(updatedPost);
};
// Deleting A Post
export const deletePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res
.status(404)
.send(`We Couldnt Found The Post With Id Of ${id} To Delete`);
await infoPost.findByIdAndRemove(id);
res.json(`Post With Id Of ${id} Deleted Succesfully`);
};
// Liking A Post
export const likePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No post with id: ${id}`);
const post = await infoPost.findById(id);
const updatedPost = await infoPost.findByIdAndUpdate(
id,
{ likeCount: post.likeCount + 1 },
{ new: true }
);
res.json(updatedPost);
};
Even though i've been trying to solve this problem for nearly 3.5 hours, i think that the problem might be in my Posts.js part, if you can help me, you're the greatest !
I have a dashboard displaying links based on user type when you register you choose your role 1, 2, 3, 4, 5. Everything works fine except when pulling data from the DB and showing it on the front end. On insomnia if I send a command adminId: 1 it returns the correct data. Below is the code where I tie the adminId to the data to display the correct links but nothing happens. If anyone can help it would be great! I am storing the adminId in userData and pulling the links from the backend using axios.
const { userData } = useContext(UserContext);
const history = useHistory();
const [links, setLinks] = useState();
const currAdmin = () => {
currAdmin = userData.user.adminId;
}
useEffect(() => {
if (!userData.user)
history.push("/");
const checkAdmin = async () => {
const adminRes = await axios.get('http://localhost:9000/Links/all', { currAdmin });
setLinks(adminRes.data);
};
checkAdmin();
});
return (
<div className="dashboard">
<Header />
<br />
<br />
<h3> Admin Type: </h3>
<ListGroup className="linklist" >
{links && links.map(e => (
<ListGroup.item key={e.adminId}>
{e.links}
</ListGroup.item>
))}
</ListGroup>
</div>
);
}
For your reference, Please let me know if it will help you.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function FetchAPIData(props) {
const [myData, setData] = useState({ data:[] });
useEffect(() => {
const fetchData = async () => {
const result = await axios(`http://dummy.restapiexample.com/api/v1/employees`,);
setData(result.myData);
};
fetchData();
}, []);
return (
<div>
<span>{JSON.stringify(myData)}</span>
<ul>
{
myData.data.map(item => {
<li key={item.id}>
{item.employee_name}
</li>
})
}
</ul>
</div>
);
}
export default FetchAPIData;
I am currently building a signup form with React, Redux, JavaScript, Node, Adonisjs. I'm attempting to upload profile images to my AWS s3 Bucket. At the moment I've got it so the file is appearing in the bucket. However when I try to click on the link provided by AWS s3 i get the following error. AWS ERROR IMAGE.
I have set my permissions to public and I have provided the correct credential keys. I'm stuck on how to solve this so any help would be greatly appreciated. Please see code below.
Below is my AWS Controller:
"use strict";
require("dotenv").config();
const aws = require("aws-sdk");
const fs = require("fs");
const Helpers = use("Helpers");
const Drive = use("Drive");
class awsController {
async upload({ request, response }) {
aws.config.update({
region: "ap-southeast-2", // AWS region
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECERT
});
const S3_BUCKET = process.env.S3_BUCKET;
const s3Bucket = new aws.S3({
region: "ap-southeast-2",
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECERT,
Bucket: process.env.S3_BUCKET
}); // Create a new instance of S3
const fileName = request.all().body.fileName;
console.log(fileName);
const fileType = request.all().body.fileType;
const params = {
Bucket: S3_BUCKET,
Key: fileName,
ContentType: fileType,
ACL: "public-read"
};
s3Bucket.putObject(params, function(err, data) {
if (err) {
response.send(err);
}
console.log(data);
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
console.log(returnData);
response.send("Success");
});
}
}
module.exports = awsController;
** Below handles uploading of file **
import React, { Component } from "react";
import axiosAPI from "./../resorterAPI";
import axios from "axios";
class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
success: false,
url: ""
};
}
handleChange = event => {};
handleUpload = event => {
let uploadedFile = this.uploadInput.files[0];
// Splits name of file
let fileParts = this.uploadInput.files[0].name.split(".");
let fileName = fileParts[0];
let fileType = fileParts[1];
let fullFileName = uploadedFile.name;
console.log("preparing upload");
axiosAPI
.post("/s3Upload", {
body: {
fileName:
Math.round(Math.random() * 1000 * 300000).toString() +
"_" +
uploadedFile.name,
fileType: fileType
}
})
.then(response => {
console.log("Success");
});
};
render() {
return (
<div>
<center>
<input
onChange={this.handleChange}
ref={ref => {
this.uploadInput = ref;
}}
type="file"
/>
<br />
<button onClick={this.handleUpload}> Upload </button>
</center>
</div>
);
}
}
export default ImageUpload;
**Below is where the image upload service is called **
import React from "react";
// Redux
import { Field, reduxForm } from "redux-form";
import { connect } from "react-redux";
import { getCountry } from "./../../redux/actions/getCountryAction.js";
import Store from "./../../redux/store.js";
// Services
import axiosAPI from "./../../api/resorterAPI";
import ImageUpload from "./../../api/services/ImageUpload";
// Calls a js file with all area codes matched to countries.
import phoneCodes from "./../../materials/PhoneCodes.json";
// Component Input
import {
renderField,
renderSelectField,
renderFileUploadField
} from "./../FormField/FormField.js";
// CSS
import styles from "./signupForm.module.css";
import classNames from "classnames";
function validate(values) {
let errors = {};
if (!values.specialisations) {
errors.firstName = "Required";
}
if (!values.resort) {
errors.lastName = "Required";
}
if (!values.yearsOfExperience) {
errors.email = "Required";
} else if (!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = "Invalid Email";
}
if (!values.spokenLanguages) {
errors.password = "Required";
}
if (values.sport !== values.confirmPassword) {
errors.confirmPassword = "Passwords don't match";
}
return errors;
}
class SignupFormStepTwo extends React.Component {
constructor(props) {
super(props);
this.state = {
countries: [],
selectedCountry: [],
dialCodes: []
};
}
// Below gets the countries from axios call made in redux actions
async componentDidMount() {
const countries = await getCountry();
// The below maps through the json file and gets all the dial codes
const codes = phoneCodes.phoneCode.map(code => {
return code.dial_code;
});
return this.setState({ countries: countries, dialCodes: codes });
}
// Handles when someone changes the select fields
handleChange = event => {
const selectedCountry = event.target.value;
return this.setState({ selectedCountry: selectedCountry });
};
// uploadFile = (values, url = "") => {
// axiosAPI.post("/displayImageUpload", { ...values, imageURL: url}).then(response => {
// console.log("Success");
// })
// }
render() {
return (
<div>
<form onSubmit={this.props.handleSubmit}>
<div className={styles.signupContainer}>
<div className={styles.signupInputContainer}>
{/* <Field
name="displayImage"
component={renderFileUploadField}
type="text"
label="Display Image"
/> */}
<ImageUpload />
<div
className={classNames({
[styles.bioField]: true,
[styles.signupInputContainer]: true
})}
>
<Field
name="bio"
component={renderField}
type="text"
label="Bio"
placeholder="Introduce yourself - Where you're from, what your hobbies are, etc..."
/>
</div>
</div>
{/* Renders the select field */}
<div className={styles.signupInputContainer}>
<Field
name="specialisations"
component={renderSelectField}
type="select"
label="Specialisations"
placeholder="Specialisations"
options={this.state.countries}
onChange={this.handleChange}
multiple={false}
/>
<Field
name="resort"
component={renderSelectField}
options={this.state.dialCodes}
type="select"
label="Resort"
placeholder="Select the resorts you can work at"
/>
<Field
name="yearsOfExperience"
component={renderSelectField}
options={this.state.dialCodes}
type="select"
label="Years of Experience"
/>
<Field
name="spokenLanguages"
component={renderSelectField}
options={this.state.dialCodes}
type="select"
label="Spoken Languages"
/>
</div>
</div>
<div className={styles.signupButtonContainer}>
<button className={styles.signupButton} type="submit">
{" "}
Submit{" "}
</button>
</div>
</form>
</div>
);
}
}
// destroyOnUnmount - saves it in state
SignupFormStepTwo = reduxForm({
form: "signupStageTwo",
destroyOnUnmount: false,
validate
})(SignupFormStepTwo);
const mapStateToProps = state => {
return {
form: state.form
};
};
export default SignupFormStepTwo;
UPDATE: Solved the error thanks to Jarmod, I was actually not separating the file extension from the file name so it was uploading image.png.png.