Home > front end >  Sanity documents not showing
Sanity documents not showing

Time:05-14

Whenever i create a new document in sanity using 'createOrReplace'. It successfully creates the document, but however it doesn't show the newly created document in the home screen.

Note: All the other documents i upload from Sanity Studio displays correctly. Only the ones created with 'createOrReplace' isn't showing

Here is my code if you want to check it:

Home.js

import { 
    View, 
    StyleSheet,
    Image,
    TouchableOpacity,
    ScrollView
} 
from 'react-native';
import React, { 
    useState,
    useEffect
 } 
from 'react';
import { 
    client, 
} 
from '../lib/client';
import CustomHeader from '../components/CustomHeader.component';
import Post from '../components/Post.component';

const Home = ({ navigation }) => {

  const [posts, setPosts] = useState([]);

    useEffect(() => {
        querySelector();
    })

  const querySelector = async () => {
      const query = `*[_type == 'post']`
      const post = await client.fetch(query);

      setPosts(post);
  }

  return (
      <>
      /* <CustomHeader screenName="Home" back={false} height={150} />
      <TouchableOpacity style={{
          position: "absolute",
          marginTop: 80,
          marginLeft: 40
      }}
      onPress={() => navigation.navigate("Create")}
      >
          <Image style={{
              height: 30,
              width: 30,
          }} source={require("../assets/Main/plus.png")} />
      </TouchableOpacity> */

     // Commented out code blocks are not necessary, the main topic is the sanity query

    <ScrollView>
        <View style={{
            display: "flex",
            flexDirection: "row",
            flexWrap: "wrap"
        }}>
            {
                posts.map(
                    post => {
                        return(
                            <>
                            <View style={{
                                display:"flex",
                                flexDirection: "row"
                            }}>
                                <Post title={post.title} desc={post.description} image={post.image} id={post._id} />
                            </View>
                            </>
                        )
                    }
                )
            }
        </View>
    </ScrollView>
    </>
  )
}

export default Home;

Create.js

import { 
    View, 
    Text, 
    StyleSheet, 
    TouchableOpacity, 
    Image, 
    Platform,
    TextInput,
    Dimensions,
    Alert
} 
from 'react-native';
import React, { 
    useState 
} 
from 'react';
import { 
    SafeAreaView 
} 
from 'react-native-safe-area-context';
import * as ImagePicker from 'expo-image-picker';
import { storage } from '../firebase/firebase-config';

const CreatePosts = ({ navigation }) => {

    const tokenWithWriteAccess = "my token";

    const [image, setImage] = useState(null);
    const [imageURL, setImageURL] = useState(null);
    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          allowsEditing: true,
          aspect: [1, 1],
          quality: 1,
        });
    
        if (!result.cancelled) {
          setImage(result);
        }

        const blob = await new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onload = () => {
              resolve(xhr.response);
            };
            xhr.onerror = (e) => {
              reject(new TypeError("Network request failed"));
            };
            xhr.responseType = "blob";
            xhr.open("GET", image.uri, true);
            xhr.send(null);
        });

        
  const metadata = { contentType: "image/jpg" };

  const imgRef = storage.ref(`${title == null ? "No" : title}/fileName`);

  await imgRef.put(blob, metadata);

  blob.close();
 
  // Image permanent URL 
  const imgURL = await imgRef.getDownloadURL();

  setImageURL(imgURL)
      };

      const createPost = async () => {
        if(title || desc !== ""){
            const mutations = [{
                createOrReplace: {
                  _id: 'p.',
                  _type: 'post',
                  title: title,
                  description: desc,
                  image: imageURL
                }
              }]
              
              await fetch(`https://projectIdHidden.api.sanity.io/v2021-06-07/data/mutate/production`, {
                method: 'post',
                headers: {
                  'Content-type': 'application/json',
                  Authorization: `Bearer ${tokenWithWriteAccess}`
                },
                body: JSON.stringify({mutations})
              })
            } else {
                return Alert.alert(
                    "Error",
                    "Please enter the title and the description"
                )
            }
        }

  return (
    <>
    <Image style={styles.background} source={require('../assets/Main/Gradiants/gradient_img.png')} />
        <SafeAreaView style={styles.androidSafeAreaView}>
            <View style={styles.container}>
                <Text style={styles.header}>
                    New Post {title == "" ? "" : `"${title}"`}
                </Text>
                <TextInput placeholder='Your Title' style={styles.title} value={title} onChangeText={text => setTitle(text)} />
                    <TextInput placeholder='Your Description' style={styles.desc} value={desc} onChangeText={text => setDesc(text)} />
                        <TouchableOpacity style={styles.imgContainer} onPress={pickImage}>
                            <Image style={styles.img} source={image == null ? require("../assets/Main/select.png") : { uri: image.uri } } />
                        </TouchableOpacity>
                            <TouchableOpacity style={image == null ? styles.postDisabled : styles.post} disabled={image == null ? true : false} onPress={createPost}>
                                    <Text style={styles.postTxt}>
                                        Post!
                                    </Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.cancel} disabled={image == null ? true : false} onPress={() => navigation.navigate("Home")}>
                                    <Text style={styles.cancelTxt}>
                                        Cancel
                                    </Text>
                        </TouchableOpacity>
                    </View>
        </SafeAreaView>
    </>
  )
}

const styles = StyleSheet.create({
    //Styles not required
})

export default CreatePosts;

CodePudding user response:

You are putting your documents on a non-root path (_id: ‘p.’), which will require a token in order to view them.

  • Related