How to upload Image from Next JS Strapi API - next.js

How can I add an image from NextJS to Strapi Media library? I Try to upload the image from the NextJS frontend, the image will be uploaded to my Strapi Media library and my Cloudinary account but the image will not be associated/linked to that particular post
Here is my code
path: components/ImageUpload.js
import { useState } from "react";
import { API_URL } from "../config/index";
import styles from "#/styles/FormImage.module.css";
export default function ImageUpload({ sportNewsId, imageUploaded }) {
const [image, setImage] = useState(null);
const handleFilechange = (e) => {
console.log(e.target.files);
setImage(e.target.files[0]);
};
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("files", image);
formData.append("ref", "sports");
formData.append("refid", sportNewsId);
formData.append("field", "image");
const res = await fetch(`${API_URL}/upload`, {
method: "POST",
body: formData,
});
if (res.ok) {
imageUploaded();
}
};
return (
<div className={styles.form}>
<h4>Upload Sport News Image</h4>
<form onSubmit={handleSubmit}>
<div className={styles.file}>
<input type="file" onChange={handleFilechange} />
<input type="submit" value="Upload" className="btn" />
</div>
</form>
</div>
);
}
path:pages/news/edit/[id].js
import Link from "next/link";
import { useState } from "react";
import Image from "next/image";
import { useRouter } from "next/router";
import moment from "moment";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Layout from "#/components/Layout";
import { API_URL } from "#/config/index";
import styles from "#/styles/FormEdit.module.css";
import Modal from "#/components/Modal";
import ImageUpload from "#/components/ImageUpload";
export default function EditNews({ sportNews }) {
const [values, setValues] = useState({
name: sportNews.name,
detail: sportNews.detail,
date: sportNews.date,
time: sportNews.time,
});
const [previewImage, setPreviewImage] = useState(
sportNews.image ? sportNews.image.formats.thumbnail.url : null
);
const [showModal, setShowModal] = useState(false);
const router = useRouter();
const { name, detail, date, time } = values;
const handleSubmit = async (e) => {
e.preventDefault();
const emptyFieldCheck = Object.values(values).some(
(element) => element === ""
);
if (emptyFieldCheck) {
toast.error("Please fill all input field");
}
const response = await fetch(`${API_URL}/sports/${sportNews.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(values),
});
if (!response.ok) {
toast.error("something went wrong!!!");
} else {
const sport = await response.json();
router.push(`/news/${sport.slug}`);
}
};
const imageUploaded = async (e) => {
const res = await fetch(`${API_URL}/sports/${sportNews.id}`);
const data = await res.json();
console.log("showing =>", data);
console.log(setPreviewImage);
setPreviewImage(data.image[0].formats.thumbnail.url);
setShowModal(false);
};
const handleInputchange = (e) => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
return (
<Layout title="Add New Sport News">
<Link href="/news">Go Back</Link>
<h2>Add Sport News</h2>
<ToastContainer />
<form onSubmit={handleSubmit} className={styles.form}>
<div className={styles.grid}>
<div>
<label htmlFor="name">Name</label>
<input
name="name"
id="name"
type="text"
value={name}
onChange={handleInputchange}
/>
</div>
<div>
<label htmlFor="date">Date</label>
<input
name="date"
id="date"
type="date"
value={moment(date).format("yyyy-MM-DD")}
onChange={handleInputchange}
/>
</div>
<div>
<label htmlFor="time">Time</label>
<input
name="time"
id="time"
type="text"
value={time}
onChange={handleInputchange}
/>
</div>
</div>
<div>
<label htmlFor="detail">Detail</label>
<textarea
name="detail"
id="detail"
type="text"
value={detail}
onChange={handleInputchange}
/>
</div>
<input className="btn" type="submit" value="Add News" />
</form>
{/* {console.log(previewImage)} */}
{previewImage ? (
<Image src={previewImage} height={100} width={180} />
) : (
<div>
<p>No Image Available</p>
</div>
)}
<div>
<button onClick={() => setShowModal(true)} className="btn-edit">
Update Image
</button>
</div>
<Modal show={showModal} onClose={() => setShowModal(false)}>
<ImageUpload sportNewsId={sportNews.id} imageUploaded={imageUploaded} />
</Modal>
</Layout>
);
}
export async function getServerSideProps({ params: { id } }) {
const res = await fetch(`${API_URL}/sports/${id}`);
const sportNews = await res.json();
return {
props: { sportNews },
};
}
this is the error message it is showing.
how do I resolve this error, any assistance will be appreciated
Thanks a lot

For a formData you have to add a header :
'Content-Type': 'multipart/form-data'
I have been struggling during hours to find this. I am uploading a file directly from an entry and not with the /upload route but it might work the same way. Using axios for the post method here is an example :
const form = new FormData();
const postData = {
name: 'test2',
};
form.append('files.image', file);
form.append('data', JSON.stringify(postData));
await axios
.post(getStrapiURL('/ingredients'), form, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((response) => {
// Handle success.
console.log('Well done!');
console.log('Data: ', response.data);
})
.catch((error) => {
// Handle error.
console.log('An error occurred:', error.response);
});

From my observation, the problem is on the setPreviewImage line remove the [0] array brackets from the image in order to access the Cloudinary thumbnail Url you will get from the Strapi API after each image upload.
The function below should make it work
const imageUploaded = async (e) => {
const res = await fetch(`${API_URL}/sports/${sportNews.id}`);
const data = await res.json();
console.log("showing =>", data);
console.log(setPreviewImage);
setPreviewImage(data.image.formats.thumbnail.url);
setShowModal(false);
};

Related

How to get the firebae document id in Vuejs 3

I'm trying to build a crud vuejs3 application (book store), and in the update operation I didn't figure out how to get the document id in order to update the book details, following are some of my code snippets where I'm currently working on:
UpdateDcoment.js
const updatingDoc = (collection, id) => {
const isPending = ref(false);
const error = ref(null);
let documentRef = db.collection(collection).doc(id);
const handleUpdateDoc = async (updates) => {
isPending.value = true;
error.value = null;
try {
const response = await documentRef.update(updates);
isPending.value = false;
console.log("update was successfully!", response);
return response;
} catch (err) {
err.value = err.message;
console.log(err.value);
error.value = err.message;
isPending.value = false;
}
};
return { error, isPending, handleUpdateDoc };
};
export default updatingDoc;
BookDetails.vue
<template>
<div>
<div v-if="document" class="book-detail-view">
<div class="book-cover">
<img :src="document.coverUrl" :alt="`${document.title} book cover`" />
</div>
<div class="book-details">
<h4 class="book-title">
{{ document.title }}
</h4>
<div class="book-description">
<p>{{ document.description }}</p>
</div>
<div class="book-author">
<p>{{ `Author: ${document.author}` }}</p>
</div>
<div v-if="currentAuthenticatedUser">
<button v-if="!isDeleting" #click="handleDelete">
Delete the book
</button>
<button v-else disabled>processing...</button>
<router-link :to="{ path: `/books/${document.id}/update` }">
Update here
</router-link>
</div>
</div>
</div>
<div v-else class="error">{{ error }}</div>
</div>
</template>
<script>
import { computed } from "#vue/runtime-core";
import getDocument from "../../controllers/getDocument";
import getUser from "../../controllers/getUser";
import deleteDocument from "../../controllers/deleteDocument";
import getStoredBook from "../../controllers/userStorage";
import { useRouter } from "vue-router";
export default {
props: ["id"],
setup(props) {
const { error, document } = getDocument("books", props.id);
const { user } = getUser();
const { removeDoc, isDeleting } = deleteDocument("books", props.id);
const { handleDeleteCover } = getStoredBook();
const router = useRouter();
const currentAuthenticatedUser = computed(() => {
return (
document.value && user.value && user.value.uid === document.value.userId
);
});
const handleDelete = async () => {
await handleDeleteCover(document.value.filePath);
await removeDoc();
router.push({ name: "home" });
};
return {
document,
error,
currentAuthenticatedUser,
handleDelete,
isDeleting,
};
},
};
</script>
UpdateBook.vue
<template>
<form #submit.prevent="handleSubmit">
<h4>Update book:</h4>
<input type="text" required placeholder="book name" v-model="title" />
<input type="text" required placeholder="author name" v-model="author" />
<textarea
required
placeholder="book description"
v-model="overview"
></textarea>
<label for="bookCover">Upload the cover book</label>
<input type="file" id="bookCover" #change="handleAddCoverBook" />
<label for="book">Upload the book</label>
<input type="file" id="book" #change="handleAddBook" />
<button v-if="!isPending">Update</button>
<button v-else disabled>Updating...</button>
<div v-if="fileError" class="error">{{ fileError }}</div>
</form>
</template>
<script>
import { ref } from "vue";
import userStorage from "#/controllers/userStorage";
import getUser from "#/controllers/getUser";
import { createdAtTime } from "#/firebase/firebaseConfig";
import { useRouter } from "vue-router";
import updatingDoc from "#/controllers/updateDocument";
export default {
setup() {
const { url1, url2, handleUploadBook, bookCoverPath, bookPath } =
userStorage();
const { user } = getUser();
const { error, isPending, handleUpdateDoc } = updatingDoc(
"books",
document.id
);
const router = useRouter();
const title = ref("");
const author = ref("");
const overview = ref("");
const bookCover = ref(null);
const book = ref(null);
const fileError = ref(null);
const handleSubmit = async () => {
if (bookCover.value) {
// Truthy value will show 'uploading...' text whenever the adding books process is processing
isPending.value = true;
await handleUploadBook(bookCover.value, book.value);
// log the result of the event listener wherever the upload was successful
console.log("book uploaded successfully", url1.value, url2.value);
const response = await handleUpdateDoc({
title: title.value,
author: author.value,
description: overview.value,
createdAt: createdAtTime(),
userId: user.value.uid,
userName: user.value.displayName,
coverUrl: url1.value,
bookUrl: url2.value,
bookCover: bookCoverPath.value,
book: bookPath.value,
});
// Truthy value will remove 'uploading...' text whenever the adding books process is finished
isPending.value = false;
if (!error.value) {
console.log("updating process successful");
router.push({ name: "BookDetail", params: { id: response.id } });
}
}
};
// Upload Cover Book
const bookCoverTypes = ["image/png", "image/jpg", "image/jpeg"];
const handleAddCoverBook = (e) => {
const newBookCover = e.target.files[0];
if (newBookCover && bookCoverTypes.includes(newBookCover.type)) {
bookCover.value = newBookCover;
fileError.value = null;
} else {
bookCover.value = null;
fileError.value = "Please add a cover book (png, jpg or jpeg)";
}
};
// Upload book
const bookTypes = ["application/pdf", "application/epub"];
const handleAddBook = (e) => {
const newBook = e.target.files[0];
if (newBook && bookTypes.includes(newBook.type)) {
book.value = newBook;
fileError.value = null;
} else {
book.value = null;
fileError.value = "Please add a book (pdf or epub)";
}
};
return {
title,
author,
overview,
handleSubmit,
handleAddCoverBook,
handleAddBook,
fileError,
isPending,
};
},
};
</script>
I'm trying to get the document id from the bookDetails.vue and then use it inside the updateBook.vue but whenever I hit the update button in the UpdateBook.vue I have the following log:
No document to update: projects/books-store-71c7f/databases/(default)/documents/books/pVIg6OytEKE4nEUE8uqd
I appreciate your hints and help guys!
SOLVED!
So, the trick was to use the params for the current URL in order to get the document id and update the document fields:
here I passing the router-link to redirect to update form:
<router-link
:to="{ name: 'UpdateBook', params: { id: document.id } }"
>
Update here
</router-link>
And here inside the setup() of the updateBook.vue component I use params to access the document id:
const router = useRouter();
// Get the current document id from the route id
const id = router.currentRoute.value.params.id;
// And here I pass the document id as parameter
const { error, isPending, handleUpdateDoc } = updatingDoc("books", id);

How to update the state in pinia with Vue 3

I'm trying to save the input values in the Pinia store, but the state is not updating. So I want onSubmit function to save the input values in a store.
My code :
Create.vue
<script setup>
import { reactive } from "vue";
import { useCounterStore } from '#/stores/counter';
const counter = useCounterStore();
const form = reactive({
first: "",
second: "",
email: ""
});
const onSubmit = (e) => {
e.preventDefault();
counter.$patch({ firstName: form.first.value });
counter.$patch({ secondName: form.second.value });
counter.$patch({ email: form.email.value });
}
</script>
<template>
<form #submit="onSubmit">
{{ counter.getFirst + 'MYFIRST' }} {{ counter.getSecond + 'MYSECOND' }} {{ counter.getEmail + 'MYEMAIL' }}
<div class="row mt-4">
<div class="col-6">
<label for="exampleFormControlInput1" class="form-label">First</label>
<input v-model="form.first" type="text" class="form-control" id="exampleFormControlInput1"
placeholder="First name">
</div> <div class="col-6">
<label for="exampleFormControlInput1" class="form-label">Second</label>
<input v-model="form.second" type="text" class="form-control" id="exampleFormControlInput1"
placeholder="Second name">
</div>
<div class="col-6 mt-2">
<label for="exampleFormControlInput1" class="form-label">Email</label>
<input v-model="form.email" type="email" class="form-control" id="exampleFormControlInput1"
placeholder="name#example.com">
</div>
<div class="col-12 mt-3">
<button #click="onSubmit" type="button" class="btn btn-dark push- right">Create</button>
<button type="button" class="btn btn-dark">All users</button>
</div>
</div>
</form>
</template>
Pinia store: counter.js
import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
let firstName = ref('');
let secondName = ref('');
let email = ref('');
const getFirst = computed(() => firstName.value)
const getSecond = computed(() => secondName.value)
const getEmail = computed(() => email.value)
function increment() {
count.value++
}
return { count, getFirst, getSecond, getEmail, increment }
})
i am not sure how your store look like... but it should by something like:
`
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
}
})`
in your component, change the name of the store instance, lets say counterStore.
const counterStore = useCounterStore();
and now you can access the state by name:
counterStore.counter++
while this will work, it is not the best practice...
you should use actions to manipulate the state...
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
},
actions: {
increment() {
this.count++
},
},
})
and then you can call the action like a regular method:
counterStore.increment()
I think you're in the process of learning Vue, don't give up!
Give a feedback in comment and put your post on "solved" status if this help you.
The solution :
In store file :
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
loginForm: {
firstName: '',
secondName: '',
email: ''
}
})
});
In Create.vue :
<script setup>
import { reactive } from "vue";
import { useAuthStore } from '#/stores/auth';
const authstore = useAuthStore();
const form = reactive({
first: "",
second: "",
email: ""
});
...
const onSubmit = (e) => {
e.preventDefault();
authStore.loginForm.firstName = form.first;
authStore.loginForm.secondName = form.second;
authStore.loginForm.email = form.email;
}
...
<script/>

What do I need to do that appendChild and addEventListener is going to work?

I can see the issue here. Stuff is going to fetch before it's still there in the order of code execution, but I don't know how to fix that at all.
I want to grab some infos from my firebase firestore database and put it in the dom in a way I can show it of nicely.
The other thing is, css file isn't working cause of the same issue. When I setAttribute to it it's already initialized and of course, it wouldn't show up at all (for example: border: 50% to make the pic round).
What do I miss to learn?
import React from "react";
import firebase from "./firebase";
import "./artists-styles.css";
const db = firebase.firestore();
const form = document.querySelector("#add-artist-avatar");
function renderArtists(doc) {
const artistsAvatar = document.querySelector(".content");
let image = document.createElement("img");
image.setAttribute("src", doc.data().avatar);
artistsAvatar.appendChild(image);
}
// getting data
db.collection("artists")
.get()
.then(snapshot => {
console.log(snapshot.docs);
snapshot.docs.forEach(doc => {
console.log(doc.data());
renderArtists(doc);
});
});
// saving data
form.addEventListener("submit", e => {
e.preventDefault();
db.collection("artists").add({
avatar: form.avatar.value,
});
form.name.value = "";
});
const Artists = () => {
return (
<div>
<h1>Cloud Cafe</h1>
<form id="add-artist-avatar">
<input type="text" name="avatar" placeholder="Artists Avatar Link" />
<button>Add Avatar</button>
</form>
<div className="content"></div>
</div>
);
};
export default Artists;
Perhaps you need something like this
import React, { useEffect, useState } from "react";
import firebase from "./firebase";
import "./artists-styles.css";
const db = firebase.firestore();
const Artists = () => {
const [docs, setDocs] = useState([]);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
db.collection("artists")
.get()
.then(snapshot => {
console.log(snapshot.docs);
setDocs(snapshot.docs);
});
}, []);
const handleSubmit = e => {
e.preventDefault();
db.collection("artists").add({
avatar: inputValue
});
};
return (
<div>
<h1>Cloud Cafe</h1>
<form id="add-artist-avatar" onSubmit={(e) => handleSubmit(e)}>
<input
type="text"
name="avatar"
placeholder="Artists Avatar Link"
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
<button>Add Avatar</button>
</form>
<div className="content">
{docs.map(doc => (
<img src={doc.data().avatar}/>
))}
</div>
</div>
);
};
export default Artists;

React Redux Input handle

I'm trying to handle simple input value using react-redux and then trying to display it. I know how to display it but i have no idea how to submit input value from component to redux store. I searched web and found nothing. Can someone explain how to do this? I'm totally new to react-redux
import React from "react";
import "./App.css";
import { connect } from "react-redux";
import { useState } from "react";
import { updateValue, addValue } from "./actions/inputActions";
function App(props) {
const [value, setValue] = useState("");
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<div className="App">
<form onSubmit={(value) => props.submitValue(value)}>
<input onChange={handleChange} value={value} type="text" />
<button type="submit">Add</button>
</form>
<h1>{props.value}</h1>
</div>
);
}
const mapStateToProps = (state) => {
return {
value: state.value,
};
};
const mapDispatchToProps = (dispatch) => {
return {
submitValue: (e, value) => {
e.preventDefault();
dispatch(addValue(value));
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
Update your onSubmit function with the value stored in your local state, like this:
<form onSubmit={(e) => {
e.preventDefault();
props.submitValue(value)
}}>
<input onChange={handleChange} value={value} type="text" />
<button type="submit">Add</button>
</form>
And your mapDispatchToProps function like this:
const mapDispatchToProps = (dispatch) => {
return {
submitValue: (value) => {
dispatch(addValue(value));
},
};
};

Updating user profile information with redux in firebase

I am trying to use Redux in my React application to update the user profile within my Firebase database from my react component.
This is my component:
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";
import { editProfile } from "../../store/actions/editProfileActions";
class UserProfile extends Component {
state = {
firstName:"",
initials:"",
lastName:""
};
onChange = e => {
this.setState({
[e.target.id]: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
console.log(this.state);
this.props.editProfile(this.state);
}
render() {
const { auth, profile } = this.props;
console.log(profile);
if (auth.isEmpty) return <Redirect to="/home" />;
return (
<div className="container">
<form onSubmit={this.onSubmit} className="white">
<h5 className="grey-text text-darken-3">Edit Profile</h5>
<div className="input-field">
<label htmlFor="title">First Name: {profile.firstName}</label>
<input type="text" id="firstName" onChange={this.onChange} />
</div>
<div className="input-field">
<label htmlFor="title">Initials: {profile.initials}</label>
<input type="text" id="initials" onChange={this.onChange} />
</div>
<div className="input-field">
<label htmlFor="title">Last Name: {profile.lastName}</label>
<input type="text" id="lastName" onChange={this.onChange} />
</div>
<div className="input-field">
<button className="btn black z-depth-0">Submit</button>
{ }
</div>
</form>
</div>
)
}
};
const mapStateToProps = state => {
return {
auth: state.firebase.auth,
profile: state.firebase.profile,
};
};
const mapDispatchToProps = dispatch => {
return {
editProfile: edit => dispatch(editProfile(edit))}
}
export default compose(
connect(mapStateToProps, mapDispatchToProps),
firestoreConnect([
{ collection: "profile"}
])
)(UserProfile);
The component correctly displays the current user information.
This is the action I have set up:
return async (dispatch, getState, { getFirestore, getFirebase }) => {
const firebase = getFirebase();
const user = await firebase
.auth()
.currentUser
.updateProfile({
firstName: profile.firstName
});
dispatch({ type: "EDITPROFILE_SUCCESS", user })
console.log("user = " + profile.firstName);
};
}
When I log the entered profile.firstName I get the entered data.
And my reducer:
const editProfileReducer = (state, action) => {
switch (action.type) {
case "EDITPROFILE_ERROR":
return {
...state,
editError: action.error
};
case "EDITPROFILE_SUCCESS":
return {
...state
};
default:
return state;
}
}
export default editProfileReducer;
Any idea what I am missing here?
In your reducer change the like below
case "EDITPROFILE_SUCCESS":
return {
...state,
user:action.user
};
Above is if you want to update the whole user object
If you want to change only name then
Let’s assume that profileName is in user object then
case "EDITPROFILE_SUCCESS":
return {
...state,
user:Object.assign({}, state.user, profileName:action.user.profileName)
};

Resources