I would like to upload a image-file to storage of the firebase and put {title , content, createDate etc} in firestore.
but it seems that state.upload file prevents putting it in firestore.
this.setState({ uploadfile: "" })
The error says
FirebaseError: Function addDoc() called with invalid data. Unsupported field value: a custom File object (found in field uploadfile in document projects/c0hQXdRAgIe1lIzq1vTy)
class CreateProject extends Component {
state = {
title:'',
content:'',
uploadfile:'',
setImageUrl:'',
}
handleChange = (e) =>{
this.setState({
[e.target.id]: e.target.value
})
}
handleSubmit = (e) =>{
e.preventDefault();
this.setState({ uploadfile: "" })
this.props.createProject(this.state)
this.props.history.push('/')
}
onDrop = acceptedFiles => {
if (acceptedFiles.length > 0) {
this.setState({ uploadfile: acceptedFiles[0] })
}
}
handleSubmitImg = (e) =>{
e.preventDefault()
//this.props.sampleteFunction()
};
parseFile = (file) =>{
const updatedFile = new Blob([file], { type: file.type });
updatedFile.name = file.name;
return updatedFile;
}
onSubmit = (event) => {
event.preventDefault();
var updatedFile = this.state.uploadfile;
if (updatedFile === "") {
}
console.log("aaaaaaaaaaaa"+updatedFile)
const uploadTask = storage.ref(`/images/${updatedFile.name}`).put(updatedFile);
uploadTask.on(
firebase.storage.TaskEvent.STATE_CHANGED,
this.next,
this.error,
this.complete
);
};
next = snapshot => {
const percent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
};
error = error => {
console.log(error);
};
complete = () => {
var updatedFile = this.state.uploadfile
storage
.ref("images")
.child(updatedFile.name)
.getDownloadURL()
.then(fireBaseUrl => {
this.setState({ setImageUrl: fireBaseUrl })
//this.state.setImageUrl(fireBaseUrl);
});
};
render() {
const maxSize = 3 * 1024 * 1024;
const dropzoneStyle = {
width: "100%",
height: "auto",
borderWidth: 2,
borderColor: "rgb(102, 102, 102)",
borderStyle: "dashed",
borderRadius: 5,
}
const {auth} = this.props
console.log("UP"+this.state.uploadfile );
if(!auth.uid) return <Redirect to="/signin" />
return (
<Dropzone
onDrop={this.onDrop}
accept="image/png,image/jpeg,image/gif,image/jpg"
inputContent={(files, extra) => (extra.reject ? 'Image files only' : 'Drag Files')}
styles={dropzoneStyle}
minSize={1}
maxSize={maxSize}
>
{({ getRootProps, getInputProps }) => (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">
Create Project
</h5>
<div className="input-field">
<label htmlFor="title">Title</label>
<input type="text" id="title" onChange={this.handleChange}/>
</div>
<div className="input-field">
<label htmlFor="content">Project Content</label>
<textarea id="content" className="materialize-textarea" onChange={this.handleChange}></textarea>
</div>
<div className="input-field">
<button className="btn pink lighten-1 z-depth-0">Create</button>
</div>
</form>
<div {...getRootProps()}>
<input {...getInputProps()} />
<p>File Drag</p>
{this.state.uploadfile ? <p>Selected file: {this.state.uploadfile.name}</p> : null}
{this.state.uploadfile ? (<Thumb key={0} file={this.state.uploadfile } />) :null}
</div>
<form onSubmit={this.onSubmit}>
<button>Upload</button>
</form>
</div>
)}
</Dropzone>
)
}
}
const matchStateToProps = (state) => {
return{
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return{
createProject: (project) => dispatch(createProject(project))
}
}
export default connect(matchStateToProps, mapDispatchToProps)(CreateProject)
Action
export const createProject = (project) => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
// make async call to database
const firestore = getFirestore();
const profile = getState().firebase.profile;
const authorId = getState().firebase.auth.uid;
firestore.collection('projects').add({
...project,
authorUserName: profile.userName,
authorId: authorId,
createdAt: new Date()
}).then(() => {
dispatch({ type: 'CREATE_PROJECT', project})
}).catch((err) => {
dispatch({ type: 'CREATE_PROJECT_ERROR', err })
})
}
};
Related
Building a simple ToDo list app in ReactJS. This page is where an existing task can be edited:
import React, {useState, useEffect} from "react";
import {PageLayout} from "../components/page-layout";
import {useParams, useNavigate} from 'react-router-dom';
import TaskDataService from "../services/TaskService";
import DatePicker from 'react-datepicker';
import FadeIn from 'react-fade-in';
import UserDataService from "../services/UserService";
export const Task = props => {
const {id} = useParams();
let navigate = useNavigate();
const initialTaskState = {
id: null,
familyId: "",
userId: "",
ownerId: "",
ownerName: "",
title: "",
description: "",
completed: false,
dueDate: new Date()
};
const [currentTask, setCurrentTask] = useState(initialTaskState);
const [message, setMessage] = useState("");
const [members, setMembers] = useState([]);
const [currentMember, setCurrentMember] = useState(null);
const [currentIndex, setCurrentIndex] = useState(-1);
const getTask = id => {
TaskDataService.get(id)
.then(response => {
setCurrentTask(response.data);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
useEffect(() => {
retrieveMembers();
}, []);
useEffect(() => {
if (id)
getTask(id);
}, [id]);
const handleInputChange = event => {
const {name, value} = event.target;
setCurrentTask({...currentTask, [name]: value});
};
const setActiveMember = (member, index) => {
setCurrentMember(member);
setCurrentIndex(index);
};
const retrieveMembers = () => {
UserDataService.listMembers()
.then(response => {
setMembers(response.data);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const updateCompleted = status => {
var data = {
id: currentTask.id,
userId: currentTask.userId,
title: currentTask.title,
ownerId: currentMember.userId,
ownerName: currentMember.firstName,
description: currentTask.description,
completed: status,
dueDate: currentTask.dueDate
};
TaskDataService.update(currentTask.id, data)
.then(response => {
setCurrentTask({...currentTask, completed: status});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const updateTask = () => {
TaskDataService.update(currentTask.id, currentTask)
.then(response => {
console.log(response.data);
setMessage("The task was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
const deleteTask = () => {
TaskDataService.remove(currentTask.id)
.then(response => {
console.log(response.data);
navigate("/tasks");
})
.catch(e => {
console.log(e);
});
};
return (
<PageLayout>
<FadeIn>
<div className="list row">
<div className="col-md-6">
{currentTask ? (
<div className="edit-form">
<h4>Task</h4>
<form>
<div className="form-group">
<label htmlFor="title" class="form-label">Title</label>
<input
type="text"
className="form-control"
id="title"
name="title"
value={currentTask.title}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="description" class="form-label">Description</label>
<input
type="text"
className="form-control"
id="description"
name="description"
value={currentTask.description}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="dueDate" class="form-label">Due Date</label>
<DatePicker
onChange={date => handleInputChange({
target: {
value: date.toISOString().split("T")[0],
name: 'dueDate'
}
})}
name="dueDate"
dateFormat="yyyy-MM-dd"
value={currentTask.dueDate.toString().split("T")[0]}
/>
</div>
<div className="form-group">
<label htmlFor="status" className="form-label">
<strong>Status:</strong>
</label>
{currentTask.completed ? " Done" : " Not Done"}
</div>
<ul className="list-group">
<label htmlFor="owner" className="form-label">Task Owner</label>
{members &&
members.map((member, index) => (
<li
className={
"list-group-item " + (index === currentIndex ? "active" : "")
}
onClick={=> setActiveMember(member, index)}
key={index}
>
{member.firstName} {member.lastName}
</li>
))}
</ul>
<div className="col-md-6">
{currentMember ? (
<div>
</div>
) : (
<div>
</div>
)}
</div>
</form>
{currentTask.completed ? (
<button
className="badge text-bg-warning mr-4"
onClick={() => updateCompleted(false)}
>
Not Done?
</button>
) : (
<button
className="badge text-bg-primary mr-2"
onClick={() => updateCompleted(true)}
>
Done!
</button>
)}
<button className="badge text-bg-danger mr-2" onClick={deleteTask}>
Delete
</button>
<button
type="submit"
className="badge text-bg-success"
onClick={updateTask}
>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br/>
<p>Please click on a Task...</p>
</div>
)}
</div>
</div>
</FadeIn>
</PageLayout>
);
};
My problem is with the member selection piece, where you can change ownership of the task:
<ul className="list-group">
<label htmlFor="owner" className="form-label">Task Owner</label>
{members &&
members.map((member, index) => (
<li
className={
"list-group-item " + (index === currentIndex ? "active" : "")
}
onClick={=> setActiveMember(member, index)}
key={index}
>
{member.firstName} {member.lastName}
</li>
))}
</ul>
...and the function where we actually update the task:
const updateTask = () => {
TaskDataService.update(currentTask.id, currentTask)
.then(response => {
console.log(response.data);
setMessage("The task was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
Selecting a new owner from the list did not actually change the ownerId/ownerName value in the task. I have figured out that this is because the new owner values live in currentMember, while the task information lives in currentTask - so I need to figure out how to get information from the updated currentMember into the proper fields in currentTask. I've monkeyed around with configurations but can't find a way to do this. Any advice?
I figured it out. The key was to define the task structure in a variable so I could specify from where the ownerId value would be pulled.
Original:
const updateTask = () => {
TaskDataService.update(currentTask.id, currentTask)
.then(response => {
console.log(response.data);
setMessage("The task was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
Updated:
const updateTask = () => {
var data = {
id: currentTask.id,
userId: currentTask.userId,
title: currentTask.title,
ownerId: currentMember.userId,
ownerName: currentMember.firstName,
description: currentTask.description,
dueDate: currentTask.dueDate
};
TaskDataService.update(currentTask.id, data)
.then(response => {
console.log(response.data);
setMessage("The task was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
I'm having a problem when I input a new url in the project's custom url.
So this url input can be edited, now when it can be edited I enter a new url behind "https://www.kutanya.com/share/", then I save and a notification "custom url is exist" appears.
my API =
export const setCustomUrl = (args, surveyId) => {
return new Promise((resolve, reject) => {
axios
.put(process.env.NEXT_PUBLIC_API_URL + `/v1/smart-survey/${surveyId}/custom-url`, args, {
headers: { Authorization: `Bearer ${token()}` },
})
.then((response) => {
resolve(response.data.data);
})
.catch((error) => {
console.log(error.response);
reject(error?.response?.data?.message || "Network error.");
});
});
};
file .jsx =
const ShareKey = ({ customUrl, surveyId, shareKey = "", setShareKey, updateUrl, refProps }) => {
const [isLoading, setIsLoading] = useState(false);
const [customInput, setCustomInput] = useState(process.env.NEXT_PUBLIC_SHARE_URL + "/");
const [active, setActive] = useState(false);
const [show, setShow] = useState(false);
const router = useRouter();
const getLink = () => {
setShareKey("");
setIsLoading(true);
automaticApproval({ surveyId })
.then((resolve) => {
console.log(resolve);
setShareKey(resolve.key);
})
.catch((reject) => {
console.log(reject);
toast.error(reject);
})
.finally(() => {
setIsLoading(false);
});
};
const toggleFunction = () => {
setActive(!active);
setShow(!show);
};
const SaveFunction = () => {
setCustomUrl({ customUrl }, router.query.surveyId)
.then((resolve) => {
console.log(resolve);
updateUrl({
customUrl
});
setShareKey(resolve.key);
toast.info("Berhasil ubah link");
})
.catch((reject) => {
console.log(reject);
toast.error(reject);
})
.finally(() => {
setIsLoading(false);
});
};
return (
<section>
<button onClick={getLink} disabled={isLoading} className={styles.link_button}>
{`GENERATE ${shareKey && "NEW "}LINK`}
</button>
{shareKey && (
<div className={styles.link_container}>
<label>Share link</label>
<div className={styles.link}>
<input
value={active ? customInput : process.env.NEXT_PUBLIC_SHARE_URL + "/" + shareKey}
onChange={(e) => {
setCustomInput(e.target.value);
}}
disabled={!active}
ref={refProps}
/>
{!show && (
<button
onClick={() => {
if (typeof navigator !== "undefined") {
navigator.clipboard.writeText(refProps.current.value);
toast.info("Copied to clipboard");
}
}}
>
copy
</button>
)}
</div>
{active ? (
<div className={styles.custom2}>
<button style={{ color: "red", marginTop: "6px" }} onClick={toggleFunction}>
Cancel
</button>
<button style={{ color: "blue", marginTop: "6px" }} onClick={SaveFunction}>
Save
</button>
</div>
) : (
<div className={styles.custom} onClick={toggleFunction}>
Create Custom URL
</div>
)}
</div>
)}
</section>
);
};
The question is, is there something wrong in my coding so that the output is 400 in the console and the notification appears?
Actions/index.js The problem is in the PostArticleAPI() function
import db, { auth, provider, storage } from "../firebase";
import { SET_USER } from "./actionType";
export const setUser = (payload) => ({
type: SET_USER,
user: payload
});
export function signInAPI() {
return (dispatch) => {
auth.signInWithPopup(provider).then((payload) => {
console.log(payload);
dispatch(setUser(payload.user));
}).catch((error) => alert(error.message));
}
}
export function getUserAuth() {
return (dispatch) => {
auth.onAuthStateChanged(async (user) => {
if (user) {
dispatch(setUser(user));
}
})
}
}
export function signOutAPI() {
return (dispatch) => {
auth.signOut().then(() => {
dispatch(setUser(null));
}).catch((error) => {
console.error(error.message);
});
}
}
export function postArticleAPI(payload) {
return (dispatch) => {
if (payload.image != '') {
const upload = storage.ref(`images/${payload.image.name}`).put(payload.image);
upload.on('state_changed', (snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log(`Progress: ${progress}%`);
if (snapshot.state === 'RUNNING') {
console.log(`Progress: ${progress}%`);
}
}, (error) => console.log(error.code),
async () => {
const downloadURL = await upload.snapshot.ref.getDownloadURL();
db.collection('articles').add({
actor: {
description: payload.user.email,
title: payload.user.displayName,
date: payload.timestamp,
image: payload.user.photoURL
},
video: payload.video,
shareImg: downloadURL,
comments: 0,
description: payload.description,
})
}
);
}
}
}
PostModal.js
import React, { useState } from 'react'
import styled from 'styled-components';
import ReactPlayer from 'react-player';
import { connect } from 'react-redux';
import { postArticleAPI } from '../actions';
import firebase from 'firebase';
const PostModal = (props) => {
const [editorText, setEditorText] = useState('');
const [shareImage, setShareImage] = useState('');
const [videoLink, setVideoLink] = useState('');
const [assetArea, setAssetArea] = useState('');
const handleChange = (e) => {
const image = e.target.files[0];
if (image === '' || image === undefined) {
alert(`not an image, the file is a ${typeof (image)}`);
return;
}
setShareImage(image);
}
const switchAssetArea = (area) => {
setShareImage("");
setVideoLink("");
setAssetArea(area);
};
const postArticle = (e) => {
console.log("heyy abay");
e.preventDefault();
if (e.target !== e.currentTarget) {
console.log("heyy abay2");
return;
}
const payload = {
image: shareImage,
video: videoLink,
user: props.user,
description: editorText,
timestamp: firebase.firestore.Timestamp.now(),
}
props.postArticle(payload);
reset(e)
}
const reset = (e) => {
setEditorText("");
setShareImage("");
setVideoLink("");
setAssetArea("");
props.handleClick(e);
};
return (
<>
{props.showModal === "open" && (
<Container>
<Content>
<Header>
<h2>Create a post</h2>
<button onClick={(e) => reset(e)}>
<img src="/images/cancel.svg" alt="cancel" />
</button>
</Header>
<SharedContent>
<UserInfo>
{props.user && props.user.photoURL ? (
<img src={props.user.photoURL} alt="" />)
: (<img src="/images/user.svg" alt="" />)}
{/* <img src="/images/user.svg" alt="" /> */}
<span>{props.user.displayName}</span>
</UserInfo>
<Editor>
<textarea value={editorText}
onChange={(e) => setEditorText(e.target.value)}
placeholder='What do you want to talk about?'
autoFocus={true}
/>
{assetArea === "image" ? (
<UploadImage>
<input type="file"
accept='image/gif, image/jpeg, image/png'
name='image'
id='file'
style={{ display: 'none' }}
onChange={handleChange}
/>
<p>
<label htmlFor="file">Select an image to share</label>
</p>
{shareImage && <img
src={URL.createObjectURL(shareImage)} />}
</UploadImage>) : (
assetArea === "media" && (
<>
<input
type="text"
placeholder="Please input a video link"
value={videoLink}
onChange={e => setVideoLink(e.target.value)}
/>
{videoLink && (<ReactPlayer width={"100%"}
url={videoLink} />)}
</>))
}
</Editor>
</SharedContent>
<ShareCreations>
<AttachAssets>
<AssetButton onClick={() => switchAssetArea("image")} >
<img src="/images/gallery.svg" alt="" />
</AssetButton>
<AssetButton onClick={() => switchAssetArea("media")}>
<img src="/images/video.svg" alt="" />
</AssetButton>
</AttachAssets>
<ShareComment>
<AssetButton>
<img src="/images/chat1.svg" alt="" />
Anyone
</AssetButton>
</ShareComment>
<PostButton disabled={!editorText ? true : false}
onClick={(e) => postArticle(e)}>
Post
</PostButton>
</ShareCreations>
</Content>
</Container>)
}
</>
)
};
//I'm hiding CSS
const mapStateToProps = (state) => {
return {
user: state.userState.user,
};
}
const mapDispatchToProps = (dispatch) => ({
postArticle: (payload) => dispatch(postArticleAPI(payload)),
});
export default connect(mapStateToProps, mapDispatchToProps)(PostModal);
Error:
TypeError: firebase__WEBPACK_IMPORTED_MODULE_0_.storage.ref is not a function
This is the error I'm getting and in this line actions/index.js
const upload = storage.ref(`images/${payload.image.name}`).put(payload.image);
It is saying storage.ref is not a function. I am getting this error that is why I'm writing this extra lines
You are probably not exporting properly the storage from ../firebase.
If you share the code from that file we can help you more. Maybe it's also a missmatch with the new Firebase API version (v9) and old one (v8).
How Should I solve this problem?
After uploading an image by react state, this state seems to prevents putting props"project" in Action in Redux.
this.setState({ uploadfile: "" })
The error says
FirebaseError: Function addDoc() called with invalid data. Unsupported field value: a custom File object (found in field uploadfile in document projects/c0hQXdRAgIe1lIzq1vTy)
class CreateProject extends Component {
state = {
title:'',
content:'',
uploadfile:'',
setImageUrl:'',
}
handleChange = (e) =>{
this.setState({
[e.target.id]: e.target.value
})
}
handleSubmit = (e) =>{
e.preventDefault();
this.setState({ uploadfile: "" })
this.props.createProject(this.state)
this.props.history.push('/')
}
onDrop = acceptedFiles => {
if (acceptedFiles.length > 0) {
this.setState({ uploadfile: acceptedFiles[0] })
}
}
handleSubmitImg = (e) =>{
e.preventDefault()
//this.props.sampleteFunction()
};
parseFile = (file) =>{
const updatedFile = new Blob([file], { type: file.type });
updatedFile.name = file.name;
return updatedFile;
}
onSubmit = (event) => {
event.preventDefault();
var updatedFile = this.state.uploadfile;
if (updatedFile === "") {
}
console.log("aaaaaaaaaaaa"+updatedFile)
const uploadTask = storage.ref(`/images/${updatedFile.name}`).put(updatedFile);
uploadTask.on(
firebase.storage.TaskEvent.STATE_CHANGED,
this.next,
this.error,
this.complete
);
};
next = snapshot => {
const percent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
};
error = error => {
console.log(error);
};
complete = () => {
var updatedFile = this.state.uploadfile
storage
.ref("images")
.child(updatedFile.name)
.getDownloadURL()
.then(fireBaseUrl => {
this.setState({ setImageUrl: fireBaseUrl })
//this.state.setImageUrl(fireBaseUrl);
});
};
render() {
const maxSize = 3 * 1024 * 1024;
const dropzoneStyle = {
width: "100%",
height: "auto",
borderWidth: 2,
borderColor: "rgb(102, 102, 102)",
borderStyle: "dashed",
borderRadius: 5,
}
const {auth} = this.props
console.log("UP"+this.state.uploadfile );
if(!auth.uid) return <Redirect to="/signin" />
return (
<Dropzone
onDrop={this.onDrop}
accept="image/png,image/jpeg,image/gif,image/jpg"
inputContent={(files, extra) => (extra.reject ? 'Image files only' : 'Drag Files')}
styles={dropzoneStyle}
minSize={1}
maxSize={maxSize}
>
{({ getRootProps, getInputProps }) => (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">
Create Project
</h5>
<div className="input-field">
<label htmlFor="title">Title</label>
<input type="text" id="title" onChange={this.handleChange}/>
</div>
<div className="input-field">
<label htmlFor="content">Project Content</label>
<textarea id="content" className="materialize-textarea" onChange={this.handleChange}></textarea>
</div>
<div className="input-field">
<button className="btn pink lighten-1 z-depth-0">Create</button>
</div>
</form>
<div {...getRootProps()}>
<input {...getInputProps()} />
<p>File Drag</p>
{this.state.uploadfile ? <p>Selected file: {this.state.uploadfile.name}</p> : null}
{this.state.uploadfile ? (<Thumb key={0} file={this.state.uploadfile } />) :null}
</div>
<form onSubmit={this.onSubmit}>
<button>Upload</button>
</form>
</div>
)}
</Dropzone>
)
}
}
const matchStateToProps = (state) => {
return{
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return{
createProject: (project) => dispatch(createProject(project))
}
}
export default connect(matchStateToProps, mapDispatchToProps)(CreateProject)
Action
export const createProject = (project) => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
// make async call to database
const firestore = getFirestore();
const profile = getState().firebase.profile;
const authorId = getState().firebase.auth.uid;
firestore.collection('projects').add({
...project,
authorUserName: profile.userName,
authorId: authorId,
createdAt: new Date()
}).then(() => {
dispatch({ type: 'CREATE_PROJECT', project})
}).catch((err) => {
dispatch({ type: 'CREATE_PROJECT_ERROR', err })
})
}
};
I am stuck around a project and honestly I don't know how to solve it (I am quite new before you judge)
so this is my code:
class EditProfile extends Component {
state = {
företagsnamn: '',
organisationsnummer: '',
};
handleChange = e => {
this.setState({
[e.target.id]: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
// console.log(this.state);
this.props.editProfile(this.state);
this.props.history.push("/dash");
};
render() {
const { auth, profile } = this.props;
if (auth.isEmpty) return <Redirect to="/dash" />;
return (
<div >
<form className="white" onSubmit={this.handleSubmit}>
<div className="row">
<div className="col xl6 l6 m6 s12">
<label>Foretagsnamn:</label>
<input
type="text"
disabled
placeholder={profile.foretagsnamn}
id="foretagsnamn"
onChange={this.handleChange}
/>
</div>
<div className="col xl6 l6 m6 s12">
<label>organisationsnummer:</label>
<input
type="number"
placeholder={profile.organisationsnummer}
id="organisationsnummer"
onChange={this.onChange}
/>
</div>
</div>
<div className="input-field">
<button className="btn orange lighten-1" style={{width:'100%'}} >Submit</button>
{ }
</div>
</form>
</div>
}}
const mapStateToProps = state => {
return {
auth: state.firebase.auth,
profile: state.firebase.profile
};
};
const mapDispatchToProps = dispatch => {
return {
editProfile: profil => dispatch(editProfile(profil))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(EditProfile);
this was the action
export const editProfile = (profil) => {
return (dispatch, getState, { getFirestore, getFirebase }) => {
const firebase = getFirebase();
const firestore = getFirestore();
const profile = getState().firebase.auth
console.log(profile)
const authorId = getState().firebase.auth.uid;
// const foretagsnamn = getFirestore().firestore.collection('users').doc(profile.uid).foretagsnamn
// firebase.auth()
firestore.collection('users').doc(profile.uid).set({
// foretagsnamn: foretagsnamn,
// organisationsnummer: profil.organisationsnummer,
adress: profil.adress,
ort: profil.ort,
telefonnummer: profil.telefonnummer,
postnummer: profil.postnummer,
}, { merge: true }
).then(() => {
dispatch({ type: 'UPDATE_SUCCESS' });
}).catch(err => {
dispatch({ type: 'UPDATE_ERROR' }, err);
});
}}
and this the reducer
const editProfileReducer = (state = initState, action) => {
switch (action.type) {
case "EDITPROFILE_ERROR":
return {
...state,
editError: action.error
};
case "EDITPROFILE_SUCCESS":
return {
...state,
user:action.user
};
default:
return state;
}
}
export default editProfileReducer;
however when I press the button submit it shows this error:
FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: undefined
PS: Solved. The action was wrong. I changed ´´´const profile = getState().firebase.auth.```**instead of profile. **
Stays open if someone needs.